首页 > 解决方案 > 将对象键值从函数推送到数组中

问题描述

在我当前的代码中,我没有得到所需的输出,因为键 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] }

标签: arraysforeachhigher-order-functions

解决方案


obj[evaluated]将if it's初始化undefined为一个空数组,并将该项推送到数组中。

如果支持,您可以使用Logical nullish assignment (??=)将空数组分配给obj[evaluated]if 它是nullor 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] }


推荐阅读