1

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?

1 Answer 1

1

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.)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.