js数组转换

新手上路,请多包涵

`

 a = [
      { linesIndex: 1,words: '我们1',start: 18},
      { linesIndex: 0,words: '我们0',start: 12},
      { linesIndex: 2,words: '我们2',start: 23},
      { linesIndex: 2,words: '我们2',start: 18},
      { linesIndex: 4,words: '我们4',start: 23},
      { linesIndex: 0,words: '我们0',start: 27},
      { linesIndex: 1,words: '我们1',start: 12},
      { linesIndex: 1,words: '我们1',start: 10}
  ]

`
转为
`

b = [
    [
     { linesIndex: 0,words: '我们0',start: 12},
     { linesIndex: 0,words: '我们0',start: 27}
    ],
    [
     { linesIndex: 1,words: '我们1',start: 10},
     { linesIndex: 1,words: '我们1',start: 12},
     { linesIndex: 1,words: '我们1',start: 18}
    ],
    [
      { linesIndex: 2,words: '我们2',start: 18},
      { linesIndex: 2,words: '我们2',start: 23},
    ],
    [],
    [
      { linesIndex: 4,words: '我们4',start: 23},
    ],
]

`

阅读 1.7k
2 个回答
let akeys = a.map(item => item.linesIndex);
// 去重
akeys = Array.from(new Set(akeys));
// 升序
akeys = akeys.sort((a,b) => a-b);
// 取最大值
let maxVal = akeys[akeys.length - 1];
let newArr = [];

// 循环最大值
for(let i=0; i<=maxVal; i++) {
    newArr[i] = [];
    for(let j=0; j< a.length; j++) {
        if (a[j].linesIndex === i) {
            newArr[i].push(a[j])
        }
    }
}

console.log(newArr)

image.png

b = a.reduce((rst, item) => {
  if (!rst[item.linesIndex]) {
    rst[item.linesIndex] = [item]
  } else {
    rst[item.linesIndex].push(item)
  }
  return rst
}, [])
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题