Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

[{
    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?

>Solution :

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading