-2

I want if the hash to be the same then all objects key attribute 'values' got merged. and I don't want to use the spread operator in my code. Here is my input:

[
  {
    "hash": "12345",
    "values": [1,2,3]
  },
  {
    "hash": "12345",
    "values": []
  },
  {
    "hash": "12345",
    "values": [4]
  },
  {
    "hash": "6789",
    "values": [9]
  },
  {
    "hash": "6789",
    "values": [1]
  }
]

Here is the output I want

[
  {
    "hash": "12345",
    "values": [1,2,3,4]
  },
  {
    "hash": "12345",
    "values": [1,2,3,4]
  },
  {
    "hash": "12345",
    "values": [1,2,3,4]
  },
  {
    "hash": "6789",
    "values": [1,9]
  },
  {
    "hash": "6789",
    "values": [1,9]
  }
]
Aqeel Khadim
  • 7
  • 2
  • 5
  • You will need to iterate over the structure of array of objects and implement the logic you want. As always, please post the code you're having trouble with if you've hit a roadblock and need debugging help. – CertainPerformance Mar 10 '23 at 07:19

1 Answers1

-1

Try this maybe

const map = arr.reduce(
    (acc, x) =>
        acc.has(x.hash)
            ? acc.set(x.hash, acc.get(x.hash).concat(x.values))
            : acc.set(x.hash, x.values),
    new Map()
)
arr.forEach(x => x.values = map.get(x.hash).sort((a, b) => a - b))

You can do that with an object as well:

const map = arr.reduce(
    (acc, x) =>
        acc[x.hash]
            ? (acc[x.hash] = acc[x.hash].concat(x.values), acc)
            : ((acc[x.hash] = x.values), acc),
    {}
)
arr.forEach(x => x.values = map[x.hash].sort((a, b) => a - b))
j-0-n-e-z
  • 313
  • 1
  • 9