I'm creating a function that accepts an array and a callback, and returns an object. It is designed to iterate through the array and perform the callback on each element. Then, each return value from the callback is 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) {
let obj = {};
let newArr = [];
//loop through each ele w/ callback
//return value saved as key in obj obj[key] = value
array.forEach(ele => {
let key = callback(ele)
obj[key] = callback(ele);
if (obj[key] === undefined) {
obj[key] = array[ele]
newArr.push(array[ele]);
} else {
newArr.push(obj[key]);
}
});
return obj;
}
The function should create arrays as values of the returned object but it doesn't. Also, it does not group array items together if the callback returns the same value when they are passed in.
Test cases(s):
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] }**
Instead I get: { 1: 1, 2: 2 }</be expected { odd: 'odd', even: 'even' } to deeply equal { odd: [ 1, 3, 5 ], even: [ 2, 4 ] }