Reputation: 107
I ran this
let nums = [6.1, 4.2, 6.2];
let numsGroup = nums.reduce((acc, num) => {
return {...acc, [Math.floor(num)]: num}
}, {});
and got the output as following // {4: 4.2, 6: 6.2}
But I need the output to be {4: [4.2], 6: [6.1, 6.2]}
Upvotes: 0
Views: 34
Reputation: 4217
using the comma operator:
let nums = [6.1, 4.2, 6.2];
let numsGroup = nums.reduce((acc, num) => (
acc[Math.floor(num)] ? acc[Math.floor(num)].push(num) : acc[Math.floor(num)] = [num]
,acc),{});
console.log(numsGroup)
Upvotes: 0
Reputation: 54649
You need to create / add to an array per number group.
let nums = [6.1, 4.2, 6.2];
let numsGroup = nums.reduce((acc, num) => {
const n = Math.floor(num);
return {...acc, [n]: [...(acc[n] ?? []), num]};
}, {});
console.log(numsGroup);
Upvotes: 1
Reputation: 5308
You are almost close, just you need to push the num into array:
let nums = [6.1, 4.2, 6.3];
let numsGroup = nums.reduce((acc, num) =>{
(acc[Math.floor(num)] ??= []).push(num);
return acc;
}, {});
console.log(numsGroup);
Upvotes: 0