Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

160
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda