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



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

相关内容

  • 没有找到相关文章

最新更新