[英]Using Javascript is there a way to push information into an array that is apart of a key/value pair?
I am having trouble with this algorithm and would love anyones support!我在使用这个算法时遇到了问题,希望得到任何人的支持!
Essentially my trouble is coming on line 7.基本上我的麻烦出现在第 7 行。
Here I manage to create a key for each element while assigning a value that matches the current key we are working with.在这里,我设法为每个元素创建一个键,同时分配一个与我们正在使用的当前键匹配的值。
But if you notice my output, instead of getting { 1: [1.3], 2: [2.1, 2.4] }
但是如果你注意到我的 output,而不是得到{ 1: [1.3], 2: [2.1, 2.4] }
Im outputting { 1: [1.3], 2: [2.4] }
.我正在输出{ 1: [1.3], 2: [2.4] }
。
function groupBy (array, callBack) {
const myObj = {};
let numsA = [];
// iterate over array
array.forEach(element => {
//each element perform callBack
myObj[callBack(element)] = [element];
// console.log(myObj)
})
// return an object
return myObj
};
const decimals = [1.3, 2.1, 2.4];
const floored = function(num) { return Math.floor(num); };
console.log(groupBy(decimals, floored));
// log: { 1: [1.3], 2: 2.4] }
// should log: { 1: [1.3], 2: [2.1, 2.4] }
Is there a.push() feature for key/value pair objects as there is for arrays?键/值对对象是否有像 arrays 那样的 a.push() 功能?
How do I add a value to the array of the 2nd key instead of overwriting it?如何向第二个键的数组添加一个值而不是覆盖它?
Try changing尝试改变
myObj[callBack(element)] = [element];
To this:对此:
if (myObj[callBack(element)] == undefined)
myObj[callBack(element)] = [element];
else
myObj[callBack(element)].push(element);
The idea is that if an array exists, the element will get added.这个想法是,如果存在数组,则将添加元素。 Otherwise, a new array is created, with the element in it.否则,将创建一个新数组,其中包含元素。
As @RobbyCornelissen pointed out, the callBack
function is ran several times.正如@RobbyCornelissen 指出的那样, callBack
function 运行了多次。 Here is a more optimized version:这是一个更优化的版本:
var output = callBack(element);
if (myObj[output] == undefined)
myObj[output] = [element];
else
myObj[output].push(element);
You can use the for in method to transverse the object and array or try array look up您可以使用 for in 方法来遍历 object 和数组或尝试数组查找
You could capture everything in a simple reduce()
operation:您可以在一个简单的reduce()
操作中捕获所有内容:
const groupBy = (array, callback) => { return array.reduce((a, v) => { const key = callback(v); a[key] = [...(a[key] || []), v]; return a; }, {}); }; const decimals = [1.3, 2.1, 2.4]; const floored = function(num) { return Math.floor(num); }; console.log(groupBy(decimals, floored));
to further Robby's contribution - you can pass the floor function right into groupBy为了进一步 Robby 的贡献 - 您可以将楼层 function 传递到 groupBy
const groupBy = (array, callback) => array.reduce((a, v) => {
const key = callback(v);
a[key] = [...(a[key] || []), v];
return a;
}, {});
const decimals = [1.3, 2.1, 2.4];
console.log(groupBy(decimals, Math.floor));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.