Hello! 欢迎来到小浪资源网!


如何根据items数组中num属性的值,从arr数组中按竖向顺序选取数据并按id排序?


如何根据items数组中num属性的值,从arr数组中按竖向顺序选取数据并按id排序?

JS数组排序处理

问题:
给定两个数组arr和items,其中arr包含可排序对象,items包含具有id和num属性的对象。根据items中num的值,按竖向顺序从arr中获取所需的数据,按id的顺序。

期望格式:

let result= [   [{price: 5, useruid: 0, item_name: '测试3'},{price: 39, useruid: 0, item_name: '测试2'},]   [{price: 20, useruid: 0, item_name: '测试2'},{price: 43, useruid: 0, item_name: '测试1'},{price: 66, useruid: 0, item_name: '测试2'},]   [{price: 23, useruid: 0, item_name: '测试1'},{price: 55, useruid: 0, item_name: '测试3'},{price: 72, useruid: 0, item_name: '测试3'},{price: 82, useruid: 0, item_name: '测试3'},{price: 97, useruid: 0, item_name: '测试3'},] ]

解决方案:

const result: (typeof arr)[0][][] = new Array(items.length)     .fill(0)     .map(() => [])  for (let flag = true, index = 0; flag; ) {     flag = false     items.forEach((v, i) => {         const a = result[i]         if (a.length < v.num) {             a.push(arr[index++])             flag = true         }     }) }  console.log(result)

相关阅读