Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

158
Views
array reduce amount value into string format

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.

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

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.

about 4 years ago · Juan Pablo Isaza Report

0

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

input.map(i => `$${i.amount}`).join('+')
about 4 years ago · Juan Pablo Isaza Report

0

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

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!