Reputation: 25
The following function does not return an array but only an object element. I do not understand why
const selectedId = selectedItems.reduce<string[]>(
(acc, curr, index) => ({
...acc,
item: curr.id
}),
[]
);
console.log('selectedId ', selectedId ); // {"item": "1"}
I want to select an array like this: item: ["1", "2", "3"]
Please any idea, who is a problem in my code?
Upvotes: 1
Views: 35
Reputation: 1074455
It returns an object because it returns whatever the last thing your callback function returned was,¹ and your callback function is returning an object (not an array).
You may have meant to use []
rather than {}
for the callback's return value (=> [...acc, item: curr.id]
), but if so, that operation is more clearly expressed via map
:
const selectedId = selectedItems.map(item => item.id);
(I'd also suggest using the plural — selectedIds
— since it holds multiple ID values.)
¹ If you use reduce
on an empty array, your callback is never called, and so the seed value you provided is returned instead. (And if you don't provide one, reduce
throws an error.)
Upvotes: 1