Home > database >  JavaScript: Merge the elements with the same key into the array
JavaScript: Merge the elements with the same key into the array

Time:11-21

I want to find duplicate elements of an array and 2 arrays of duplicate elements.

array = [
  ["41",{asd:"1"}],
  ["41",{asd:"2"}],
  ["42",{asd:"1"}],
  ["42",{asd:"2"}]
]

And the result I want

result=[
  ["41",{asd:"1"},{asd:"2"}],
  ["42",{asd:"1"},{asd:"2"}],
]

I have to use core JavaScript. Frameworks are not allowed.

CodePudding user response:

  • Using Array#reduce, iterate over the array while updating a Map where the key is the number and the value is its list of objects
  • Using Array#map, return a list of arrays with each number and its objects in one array

const array = [ ["41", {asd:"1"}], ["41", {asd:"2"}], ["42", {asd:"1"}], ["42", {asd:"2"}] ];

const res = [...
    array.reduce((map, [key, obj]) => 
      map.set(key, [...(map.get(key) || []), obj])
    , new Map)
    .entries()
  ]
  .map(([key, objArr]) => [key, ...objArr]);

console.log(res);
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

reduce over the array. Extract the key and object from the array in each iteration. If the key doesn't exist on the accumulator add it and set it's value to [key], and then push the object into it. Then use Object.values to get the output you need.

const arr = [
  ["41",{asd:"1"}],
  ["41",{asd:"2"}],
  ["42",{asd:"1"}],
  ["42",{asd:"2"}]
];

const out = arr.reduce((acc, c) => {
  const [key, obj] = c;
  acc[key] = acc[key] || [key];
  acc[key].push(obj);
  return acc;
}, {});

console.log(Object.values(out));
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related