ember.js 基于多个值的组数组

lhcgjxsq  于 2022-11-05  发布在  其他
关注(0)|答案(1)|浏览(154)

我想对以下产品进行分组:-

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"}]

例如,如果连续产品的日期和名称相似,并且第一个产品的“开始”与下一个产品的“结束”相同,则应将第一个产品的“开始”与下一个产品的“结束”进行分组。

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"}]

最好使用Foreach循环而不是for循环。

xhv8bpkk

xhv8bpkk1#

利用reduce函数来实现所需的结果。

var 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"}];

var result = array.reduce((acc, elem)=>{
   index = acc.findIndex(val=>val.to == elem.from && val.date == elem.date && val.name==elem.name);
   index == -1 ? acc.push(elem) : acc[index].to = elem.to
   return acc;
},[]);

console.log(result);

希望这能帮上忙谢谢!

相关问题