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

173
Vistas
Array of arrays, get first element and length. Javascript

Here is picture of my data I have:

console.log

Im trying to get array of objects, which will look like this:

[{
    length: 2,
    item: {
       imgSource: "/sushi/test2.png"
       ingredients: "Nori, Cucumber, Rice, Cream cheese, Sesame, Unagi sauce"
       name: "sushi1"
       price: 133
       weight: 120}
}, 

{   
    length: 1,
    item: {
       imgSource: "/sushi/test1.png"
       ingredients: "Salmon, Nori, Cucumber, Rice, Cream cheese"
       name: "sushi2"
       price: 119
       weight: 120}
}]

The best way i think of is to use reduce function, but i have no idea how to use it right, can anyone help me?

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

0

  1. Make a loop through all items of your array

  2. Compare objects of the current item and the result array (How to determine equality for two JavaScript objects?)

  3. If the same item found - inc the value "length" of that result array.

  4. If it is not found - add a new item to the result array with the length = 1

about 4 years ago · Juan Pablo Isaza Denunciar

0

It's pretty simple actually:

var items = [
   [{
      imgSource: "/sushi/test2.png",
      ingredients: "Nori, Cucumber, Rice, Cream cheese, Sesame, Unagi sauce",
      name: "sushi1",
      price: 133,
      weight: 120,
   }, {
      imgSource: "/sushi/test2.png",
      ingredients: "Nori, Cucumber, Rice, Cream cheese, Sesame, Unagi sauce",
      name: "sushi1",
      price: 133,
      weight: 120,
   }],

   [{
      imgSource: "/sushi/test1.png",
      ingredients: "Salmon, Nori, Cucumber, Rice, Cream cheese",
      name: "sushi2",
      price: 119,
      weight: 120,
   }]
]

items = items.reduce(function(carry, item) {
    if (!carry.hasOwnProperty(item.name)) {
      carry.push({
        count: item.length,
        item: item[0]
      })
    }
    return carry;
}, [])

console.log(items)

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