I am having trouble with this algorithm and would love anyones support!
Essentially my trouble is coming on line 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] }
Im outputting { 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?
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. 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
You could capture everything in a simple reduce()
operation:
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
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));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.