arrays - 将对象键值从函数推送到数组中
问题描述
在我当前的代码中,我没有得到所需的输出,因为键 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] }
解决方案
obj[evaluated]
将if it's初始化undefined
为一个空数组,并将该项推送到数组中。
如果支持,您可以使用Logical nullish assignment (??=)
将空数组分配给obj[evaluated]
if 它是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] }
推荐阅读
- angularjs - 在 AWS EC2 服务器上托管 Angular App、ExpressJS 端点
- vue.js - Vuetify - 在过渡期间隐藏导航抽屉
- html - 在 android 浏览器/cordova 上滚动太远时摆脱阴影
- uwp - 尝试在 Direct2D UWP (C++/WinRT) 项目中渲染路径几何时出错
- simulation - Eclipse Schlumberger 100 石油工程
- c# - 如何防止在多个测试方法之间共享 Sqlite 内存存储
- node.js - Strongloop/loopback 4:如何通过 REST 禁用 Explorer 组件的身份验证?
- apache-spark - 当 Kubernetes 上的进程终止时,spark-submit 不会终止驱动程序
- python - 允许 Networkx 中的重复节点/防止节点在树图中有两个父节点
- microsoft-graph-api - 将 MS Graph 访问权限从一个帐户授予其他帐户 - 可能吗?