Kevin.a
Kevin.a

Reputation: 4296

Returning an object after reduce function

Im trying to use reduce in combination with the spread operator to practice. I have an array that i wish to convert into an object. I tried doing this, but my reduce function only returns the last value of the array. I wish this reducer function to add on to the array.

My try :

const arr = ['1' , '4' , '3' , '5' , '3'];

let obj;
arr.reduce((acc ,val) => {
    obj = {...acc , [val]:val};
},{});

console.log(obj)

Why do i only get the last value? and not the entire array to an object?

Upvotes: 2

Views: 2953

Answers (3)

bigh_29
bigh_29

Reputation: 2633

You need to return the new value of the accumulator out of the reducing function

const arr = ['1' , '4' , '3' , '5' , '3'];

const obj = arr.reduce((acc ,val) => {
    return {...acc , [val]:val};
},{});

console.log(obj);

You can shorten that a bit further by returning the object literal wrapped in parentheses. See returning object literals

const arr = ['1' , '4' , '3' , '5' , '3'];

const obj = arr.reduce((acc ,val) => ({...acc , [val]:val}), {});

console.log(obj);

Upvotes: 1

briosheje
briosheje

Reputation: 7446

The reduce callback expects a return if expressed like you did. In your scenario, nothing is returned from your reduce callback, because obj is assigned but never returned, hence acc in the second iteration is not defined and obj is assigned in each cycle, resulting in the last element of arr spread to an object.

If you want to do that in a single line, you can also avoid assigning to obj, by just using reduce as intended, by spreading progressively to a brand new object. The value returned by reduce will be assigned to obj.

const arr = ['1' , '4' , '3' , '5' , '3'];

let obj = arr.reduce((acc, val) => ({...acc, [val]: val}), {});
//                                                         ^--- initial value
console.log(obj);

Upvotes: 4

Krzysztof Krzeszewski
Krzysztof Krzeszewski

Reputation: 6714

That's because you did not return the balue from reduce

const arr = ['1' , '4' , '3' , '5' , '3'];

let obj = arr.reduce((acc ,val) => {
    const obj = {...acc , [val]:val};
    return obj;
},{});

console.log(obj)

or simplified

const arr = ['1', '4', '3', '5', '3'];
const obj = arr.reduce((acc, val) => ({ ...acc,[val]: val}), {});
console.log(obj)

Upvotes: 1

Related Questions