Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

merge sub-array if other key-value pair match

I have this simple array, which I want to merge key b value if key a in the whole array matches.

const array = [
  {a: 1, b: ['Foo']},
  {a: 1, b: ['Bar']},
  {a: 1, b: ['Baz']},
  {a: 2, b: ['Foo']},
  {a: 3, b: ['Foo']},
]

into

const array = [
  {a: 1, b: ['Foo','Bar','Baz']},
  {a: 2, b: ['Foo']},
  {a: 3, b: ['Foo']},
]

is there a way to do it? Any help would be appreciated!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

EDIT 1 : What I am lacking here is the logic to grab all similar key a

>Solution :

Use reduce to iterate over the array of objects to create an object where the keys match the object’s a value, adding the various b values to their arrays. Then use Object.values to create a new array.

const arr = [
  {a: 1, b: ['Foo']},
  {a: 1, b: ['Bar']},
  {a: 1, b: ['Baz']},
  {a: 2, b: ['Foo']},
  {a: 3, b: ['Foo']},
];

// For each iteration pass in the accumulator
// and the current object
const out = arr.reduce((acc, c) => {

  // Assign the value of `a` to `key`
  const key = c.a;
  
  // If the key doesn't exist on the accumulator
  // set a new object
  acc[key] = acc[key] || { a: key, b: [] };

  // And then push the first element of `b`
  // into the object's array
  acc[key].b.push(c.b[0]);

  // Return the accumulator
  return acc;

}, {});

// And then finally get the Object.values from
// your returned object to make an array
console.log(Object.values(out));
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading