Home > Software design >  How to iterate through map and push keys with similar values into the same array?
How to iterate through map and push keys with similar values into the same array?

Time:07-12

I've got javascript map with structure like this:

let map = {3 => 1,
           15 => 2,
           0 => 2,
           8 => 3,
           9 => 3}

I need to receive the arrays of keys, and keys with similar values should be in the same array.

[[3], [15,0],[8,9]]

This is what I've tried:

    let answers = [];
    let currentVal = 1;
    map.forEach((value, key)=>{
      let subArr = [];
      if(value === currentVal){
        subArr.push(key);
        answers.push(subArr);
        currentVal  ;
   }

    });
    
    return answers;

And it returns [[3], [15], [8]]

CodePudding user response:

I assume your map is an object, not map for readability reasons, but if u are using Map there you can change methods to get elements but main idea you can see below:

const data = {
  3: 1,
  15: 2,
  0: 2,
  8: 3,
  9: 3
};

const customData = Object.entries(data).reduce((acc, [key, value]) => {
  if (value in acc) {
    acc[value].push(key);
  } else {
    acc[value] = [key];
  }

  return acc;
}, {});

const finalArray = Object.values(customData);
console.log(finalArray);

Edit with Map() example:

const data = new Map([
  [3, 1],
  [15, 2],
  [0, 2],
  [8, 3],
  [9, 3]
]);

const customData = Array.from(data).reduce((acc, [key, value]) => {
  if (value in acc) {
    acc[value].push(key);
  } else {
    acc[value] = [key];
  }

  return acc;
}, {});

const finalArray = Object.values(customData);
console.log(finalArray);

CodePudding user response:

You could use Object.entries and destructuring key, value but I change their place as value, key to match the data structure map provided by OP :

let map = { 3: 1, 15: 2, 0: 2, 8: 3, 9: 3 };
const arr = [];
for (const [value, key] of Object.entries(map)) {
  if (arr[key]) {
    arr[key].push(value);
  } else {
    arr[key] = [value];
  }
}
console.log(arr.filter(Boolean)); // [[3], [15,0],[8,9]]

NOTE arr.filter(Boolean) to remove falsy (empty) values from array since index 0 have no array inside of it!

  • Related