jeudi 14 mai 2020

Group array based on many values

I want to group the following array of products:-

const array = [{date: "10 feb", from: "2", to: "10", name:"chair"},
               {date: "10 feb", from: "10", to: "22", name: "chair"}, 
               {date: "10 feb", from: "22", to: "31", name: "chair"}, 
               {date: "10 feb", from: "35", to: "40", name: "chair"}, 
               {date: "12 feb", from: "2", to: "10", name: "chair"}, 
               {date: "12 feb", from: "10", to: "20", name: "toy"}]

Such as if the date and name of consecutive product are similar and also "from" of 1st product is same as "to" of the next product then they should be grouped by taking "from" of 1st product and "to" of next product.

Result array = [{date: "10 feb", from: "2", to: "31", name:"chair"},
                {date: "10 feb", from: "35", to: "40", name: "chair"},
                {date: "12 feb", from: "2", to: "10", name: "chair"}, 
                {date: "12 feb", from: "10", to: "20", name: "toy"}]

Preferable solution using Foreach loop rather than for loop.




Aucun commentaire:

Enregistrer un commentaire