Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
114 views
in Technique[技术] by (71.8m points)

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

`


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...