问答

js数组转换

作者:admin 2021-06-12 我要评论

` a = [ { linesIndex: 1,words: '我们1',start: 18}, { linesIndex: 0,words: '我们0',start: 12}, { linesIndex: 2,words: '我们2',start: 23}, { linesIndex:...

在说正事之前,我要推荐一个福利:你还在原价购买阿里云、腾讯云、华为云服务器吗?那太亏啦!来这里,新购、升级、续费都打折,能够为您省60%的钱呢!2核4G企业级云服务器低至69元/年,点击进去看看吧>>>)

`

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

`

###
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
}, [])

版权声明:本文转载自网络,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。本站转载出于传播更多优秀技术知识之目的,如有侵权请联系QQ/微信:153890879删除

相关文章
  • js数组转换

    js数组转换

  • 卷积神经网络

    卷积神经网络

  • React Native 要如何进行性能调试

    React Native 要如何进行性能调试

  • 使用docker 搭建本地接口测试服务DOCle

    使用docker 搭建本地接口测试服务DOCle

腾讯云代理商
海外云服务器