Home > Back-end >  Pushing object key values into an array from a function
Pushing object key values into an array from a function

Time:10-05

In my current code, I do not get the desired output because the value of the key obj[2] gets updated to 2.4 since the value is a number and not an array.

Is there a simple way to store the property values as an array and push these elements onto the array? (see instructions in code)

// Create a function groupBy that accepts an array and a callback, and returns an object. groupBy will iterate through the array and perform the callback on each element. 
// Each return value from the callback will be saved as a key on the object. 
// The value associated with each key will be an array consisting of all the elements 
//that resulted in that return value when passed into the callback.

function groupBy(array, callback) {
  const obj = {};

  array.forEach((el) => {
    const evaluated = callback(el);
    obj[evaluated] = el

  });
  return obj
}
//current output : {1: 1.3, 2: 2.4}

const decimals = [1.3, 2.1, 2.4];
const floored = function(num) {
  return Math.floor(num);
};
console.log(groupBy(decimals, floored)); // should log: { 1: [1.3], 2: [2.1, 2.4] }

CodePudding user response:

Initialize the obj[evaluated] if it's undefined to an empty array, and push the item to the array.

If supported you can use the Logical nullish assignment (??=) to assign an empty array to obj[evaluated] if it's null or undefined:

function groupBy(array, callback) {
  const obj = {};

  array.forEach((el) => {
    const evaluated = callback(el);
    (obj[evaluated] ??= []).push(el);
  });
  
  return obj
}

const decimals = [1.3, 2.1, 2.4];
const floored = function(num) {
  return Math.floor(num);
};
console.log(groupBy(decimals, floored)); // should log: { 1: [1.3], 2: [2.1, 2.4] }

  • Related