Harshit Badolla
Harshit Badolla

Reputation: 107

How to group similar items in array together using reduce and return an objext using arr.reduce?

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

Answers (3)

Alan Omar
Alan Omar

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

Yoshi
Yoshi

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

Rajneesh
Rajneesh

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

Related Questions