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



如何根据物品数量和名称对商品价格数组进行分组排序?


avatar
1986424546 2024-11-19 29

如何根据物品数量和名称对商品价格数组进行分组排序?

JS数组排序处理

如何根据给定的物品数量,对带有价格和物品名称的数组进行排序,使其以物品名称和价格为准进行竖向排列

问题详述:

给定数组:

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

期望输出:

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)

输出:

[   [     { 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" }   ] ]

相关阅读