Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

172
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!