将对象键值从函数推入数组

Pushing object key values into an array from a function

在我当前的代码中,我没有得到所需的输出,因为键 obj[2] 的值更新为 2.4,因为该值是数字而不是数组。

有没有一种简单的方法可以将 属性 值存储为数组并将这些元素推送到数组中? (见代码说明)

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

如果 undefined 为空数组,则将 obj[evaluated] 初始化为一个空数组,并将项目推入数组。

如果支持,您可以使用 Logical nullish assignment (??=) 将空数组分配给 obj[evaluated],如果它是 nullundefined:

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