1. 首页 > 快讯

根据商品名称求和(物品名称单价数量总价)

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" }
  ]
]
登录后复制

本文采摘于网络,不代表本站立场,转载联系作者并注明出处:https://www.iotsj.com//kuaixun/7582.html

联系我们

在线咨询:点击这里给我发消息

微信号:666666