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

How to loop and push on the accumulator of a reduce function?

I’m trying to reduce an array, and transform it in multiple array.

  const array = [
    { a: 1, b: 6 },
    { a: 1, b: 5 },
    { a: 1, b: 6 },
    { a: 1, b: 4 },
    { a: 1, b: 5 }
  ];

  var newArray = array.reduce(
    (memo, curr) => {
      memo.forEach((item, key) => {
        const found = item.filter((el) => el.a === curr.a && el.b === curr.b);
        if (found.length > 0) return memo[key].push(curr);
        else return memo.push([curr]);
      });

      return memo;
    },
    [[]]
  );

The needed result I try to get is

 [
    [
      { a: 1, b: 5 },
      { a: 1, b: 5 }
    ],
    [
      { a: 1, b: 6 },
      { a: 1, b: 6 },
    ],
    [
      { a: 1, b: 4 },
    ]
 ];

But as you can see if you try, because I push on the memo, the loop continue to fire. And the result contain hundreds arrays.

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

How I’m supposed to do to limit this loop and get the right result ?

Thanks a lot in advance 🙂

>Solution :

You could use Map to group the element by the key of {a, b}, and then get the values of the group

const array = [
  { a: 1, b: 6 },
  { a: 1, b: 5 },
  { a: 1, b: 6 },
  { a: 1, b: 4 },
  { a: 1, b: 5 },
];

var newArray = Array.from(
  array
    .reduce((map, curr) => {
      const key = JSON.stringify({ a: curr.a, b: curr.b });

      if (!map.has(key)) {
        map.set(key, []);
      }

      map.get(key).push(curr);

      return map;
    }, new Map())
    .values()
);

console.log(newArray);
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