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

130
Vistas
Manipulate objects in an array to include an array of other values in found in sibling objects

I have an array that looks like this (simplified):

[
  {
    name: 'Store1',
    price: ['10'],
    somethingElse: null
  },
  {
    name: 'Store2',
    price: ['5'],
    somethingElse: 6
  },
  {
    name: 'Store2',
    price: ['15'],
    somethingElse: 6
  },
]

I need to turn it into this:

[
  {
    name: 'Store1',
    price: ['10'],
    somethingElse: null
  },
  {
    name: 'Store2',
    price: ['5', '15'],
    somethingElse: 6
  },
]

So for each object where the name is the same, it takes the price's for all of them and puts them in an array, and reduces amount of entries with the same name to one.

It needs to work for a much longer array, and work with many name's.

Let's assume that everything other than the price will be the same in each object that has the same name.

I have tried for too long using array.reduce but with no luck.

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

const input = [
  {
    name: 'Store1',
    price: ['10'],
    somethingElse: null
  },
  {
    name: 'Store2',
    price: ['5'],
    somethingElse: 6
  },
  {
    name: 'Store2',
    price: ['15'],
    somethingElse: 6
  },
]

const output = input.reduce((a,c) => {
if(a.find(i => i.name === c.name)) { // Check if 'name' already exist 
    return a.map(el => el.name === c.name ? ({...el, price: [...el.price, ...c.price]}) : el) // updating price for existed name
} else {
    return [...a, c] // no such name, should add to ouput result
}
}, [])

console.log(output)

about 4 years ago · Juan Pablo Isaza Denunciar

0

You can use grouping by hash approach:

const data = [{"name":"Store1","price":["10"],"somethingElse":null},{"name":"Store2","price":["5"],"somethingElse":6},{"name":"Store2","price":["15"],"somethingElse":6}];

const result = Object.values(data.reduce((acc, obj) => {
  acc[obj.name] ??= obj;
  if (!acc[obj.name].price.includes(...obj.price)) 
    acc[obj.name].price.push(...obj.price);

  return acc;
}, {}));

console.log(result);
.as-console-wrapper{min-height: 100%!important; top: 0}

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