数组转换想要的数组?

作者站长头像
站长
· 阅读数 11

let data=[{id:1,width:500,height:1000},{id:2,width:500,height:1000},{id:3,width:500,height:500},{id:4,width:500,height:500},{id:5,width:500,height:1000},{id:6,width:500,height:1000},{id:7,width:500,height:500},{id:8,width:500,height:500},{id:9,width:500,height:500},{id:10,width:500,height:500},]

let data2=[{id:1,slot:1,list:[{width:500,height:1000},{width:500,height:1000}]},{id:2,slot:0,list:[{width:500,height:500},{width:500,height:500}]},{id:3,slot:1,list:[{width:500,height:1000},{width:500,height:1000}]},{id:4,slot:0,list:[{width:500,height:500},{width:500,height:500},{width:500,height:500},{width:500,height:500}]},]

数组一怎么转换为数组二呢 ,相邻的高度相等放在一起

回复
1个回答
avatar
test
2024-06-21
const exchange = list => list.reduce((res, v) => {
  const prev = res[res.length-1];
  if(prev?.list[0].height === v.height) prev.list.push({width: v.width, height: v.height});
  else res.push({id: res.length+1, slot: 1-res.length%2, list: [{width: v.width, height: v.height}]})
  return res;
}, [])


exchange([
  {id:1,width:500,height:1000},
  {id:2,width:500,height:1000},
  {id:3,width:500,height:500},
  {id:4,width:500,height:500},
  {id:5,width:500,height:1000},
  {id:6,width:500,height:1000},
  {id:7,width:500,height:500},
  {id:8,width:500,height:500},
  {id:9,width:500,height:500},
  {id:10,width:500,height:500},
])
回复
likes
适合作为回答的
  • 经过验证的有效解决办法
  • 自己的经验指引,对解决问题有帮助
  • 遵循 Markdown 语法排版,代码语义正确
不该作为回答的
  • 询问内容细节或回复楼层
  • 与题目无关的内容
  • “赞”“顶”“同问”“看手册”“解决了没”等毫无意义的内容