array reduce amount value into string format

Viewed 35

I have an array of items, where i need to get a string of each product price.

const input = [{id: 1, amount: 20}, {id: 2, amount: 40}, {id: 3, amount: 90}]

const output = input?.reduce((acc, curr) => {
        acc += `$${curr.amount}+`;
        return acc;
      }, '')

console.log(output)

Expected output is $20+$40+$90

But when i am trying this code i am getting the sum as $150 and i don't want to have + at the last if there are no more items.

5 Answers

Why Array.reduce()? This is a classic example for Array.map():

const input = [{id: 1, amount: 20}, {id: 2, amount: 40}, {id: 3, amount: 90}]

const expression = input.map(
  ({ amount }) => `$${amount}`     // destructure the object, keep only .amount
).join('+');

console.log(expression);

Read about destructuring in the JavaScript documentation.

You can use map to extract the values followed by a join to create the string.

input.map(i => `$${i.amount}`).join('+')

Use split, and your code almost works

const input = [{id: 1, amount: 20}, {id: 2, amount: 40}, {id: 3, amount: 90}]

const output = input?.reduce((acc, curr) => {
        acc.push(curr.amount + "$");
        return acc;
      }, []).join("+")

console.log(output)

const input = [{ id: 1, amount: 20 }, { id: 2, amount: 40 }, { id: 3, amount: 90 }]

const output = input?.slice(1).reduce((acc, curr) => {
    acc += `+$${curr.amount}`;
    return acc;
}, input.length ? `$${input[0].amount}` : '');

console.log(output)

with minimum manipulation

To add to the answers, we can use the currentIndex in the callback function in reduce as the third argument.

const input = [{id: 1, amount: 20}, {id: 2, amount: 40}, {id: 3, amount: 90}, {id: 4, amount: 55}]

const output = input?.reduce((acc, curr, index) => {
        acc += `$${curr.amount}`;
        if (index < input.length - 1) acc += '+'
        return acc;
      }, '')

console.log(output)

`

Related