Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

174
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda