-3

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?

Dima Malko
  • 227
  • 2
  • 19

2 Answers2

1
  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

1

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)
shaedrich
  • 5,457
  • 3
  • 26
  • 42
  • How can you add an answer when there's no question or problem? o.O – Andreas Feb 18 '22 at 14:21
  • 1
    The question is implicit. So much for the 'how'. But considering your 'why', you're right. I should have flagged this question. Sometimes, I'm eager to help and should pay more attention. – shaedrich Feb 18 '22 at 14:23
  • _"The question is implicit. So much for the 'how'"_ - The "blue i" tells a different story. – Andreas Feb 18 '22 at 14:24
  • Which "blue i"? The one from the screenshot? – shaedrich Feb 18 '22 at 14:24
  • Yes. The logged array is changed later in time. Nothing in the "question" indicates such an asynchronous action. So this is not the whole story. – Andreas Feb 18 '22 at 14:25
  • What about asking that in the comments below the question. That's something I can't give you an answer to. – shaedrich Feb 18 '22 at 14:26
  • Just don't answer unclear and zero-effort "questions". Especially nice to answer and then to close-vote. Oh sweet reputation... – Andreas Feb 18 '22 at 20:20