How to add value in an array in an object

How can I add 2.1 before 2.4…?

function groupBy(arr, cb) {
  const resultObj = {};
  arr.map(el => { resultObj[cb(el)] = [el];
  });
  return resultObj;
}

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] }

I think you are overwriting the 2 property of your object.

...
arr.forEach(el => {
  var x = cb(el)
  if(resultObj.hasOwnProperty(x)])) {
    resultObj[x].push(el)
} else {
  resultObj[x] = [el]
}
})
return resultObj
1 Like
function groupBy(arr, cb) {
     const resultObj = {};
     arr.forEach((el) => {
           if (!resultObj[cb(el)]){
                resultObj[cb(el)] = [el];
                return;           
           }
           resultObj[cb(el)].push(el);
     });
     return resultObj;
}

I changed your map() to forEach() since you don’t need a return array.
I added an if statement checking if a particular key exists. If it does not,. create it, if it does, push to its array.

1 Like