1

i need to find the repeated values in an array like this:

let arr = [
     {date:"20/7/2020", state:"walking",duration:"20"},
     {date:"21/7/2020", state:"driving",duration:"13"},
     {date:"20/7/2020", state:"walking",duration:"39"},
     {date:"21/7/2020", state:"driving",duration:"76"},
]

I need to take as reference the equal date and state between all the objects that meet that equality, then sum their durations and push them in an array, but I can't find the way

Manuel
  • 11
  • 2
  • sort & iterate or populate hash table – amit Feb 04 '21 at 18:21
  • [This thread](https://stackoverflow.com/q/7055508/572670) has some information about the theoretic aspects of the problem, as well as some practical solutions – amit Feb 04 '21 at 18:23
  • https://stackoverflow.com/questions/840781/get-all-non-unique-values-i-e-duplicate-more-than-one-occurrence-in-an-array this will help – gugateider Feb 04 '21 at 18:24
  • You can create a map or an object to know the repeated values using date and/or the state as a key for example. I would use it reduce and filter. try to make an effort and upload your code to know what you did. – Oscar López Feb 04 '21 at 18:24

1 Answers1

0

Maybe use reduce?

const newArr = Object.values(arr.reduce((acc, { date, state, duration }) => {
  acc[date+state] = (acc[date+state] || 0) + +duration
  return acc
}, {}))

Or something like

arr.reduce((acc, { date, state, duration }) => {
  if (!acc[state]) {
    acc[state] = {}
  }
  acc[state][date] = (acc[state][date] || 0) + +duration
  return acc
}, {})

And some logic with Object.keys() and sort()

St1ggy
  • 53
  • 4