Company logo
  • Empleos
  • Bootcamp
  • Acerca de nosotros
  • Para profesionales
    • Inicio
    • Empleos
    • Cursos y retos
    • Preguntas
    • Profesores
    • Bootcamp
  • Para empresas
    • Inicio
    • Nuestro proceso
    • Planes
    • Pruebas
    • Nómina
    • Blog
    • Calculadora

0

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

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

7 months 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}

7 months 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 empleo Planes Nuestro proceso Comercial
Legal
Términos y condiciones Política de privacidad
© 2023 PeakU Inc. All Rights Reserved.