r/JavaScriptHelp • • Mar 14 '22

❔ Unanswered ❔ Get count and format

I have an object dateRange ={ 2021-08-06 - 2021-09-06 : 0, 2021-09-06 -2021-10-06 : 0}

I also have another array dateArr=[2021-08-06, 2021-11-06]. Desired res = [{key: 2021-08-06 - 2021-09-06 , value: 1}, { key: 2021-09-06 -2021-10-06 , value: 0}] where value contains the number of occurrences of values inside dateArr as per dateRange.

How can I achieve this?

2 Upvotes

3 comments sorted by

1

u/trplclick Mar 14 '22

This should achieve what you want. I've commented it so it should be easy to follow, but any questions let me know!

const result = {}

const dateArr = ['2021-08-06', '2021-11-06', '2021-08-06', '2021-13-06']

// Loop through each item in the dateArr array
for (let i = 0; i < dateArr.length; i++) {
  // Get the value for the current iteration of the loop
  const date = dateArr[i]
  
  // If the results object hasn't seen this value before then define it.
  // It starts as zero so that the last line can always increment.
  if (!result[date]) {
    result[date] = 0
  }
  
  // Increment the number of times we've seen this date by 1.
  result[date]++
}

console.log(result)

I've also created a JS bin so you can see it working and play around with it if you like. https://jsbin.com/lezatupeqi/edit?js,console

1

u/killMeSak Mar 14 '22

u/trplclick The dateRange looks like below:
const dateRange = {
"2021-08-06 - 2021-09-06": 0,
"2021-09-06 - 2021-10-06": 0
}

In your code, how are we fetching each key of dateRange and comparing it?

1

u/killMeSak Mar 14 '22

http://jsfiddle.net/vdfo3tzn/ ADded a fiddle for reference