登录
首页 >  文章 >  前端

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

时间:2024-11-23 08:19:05 202浏览 收藏

偷偷努力,悄无声息地变强,然后惊艳所有人!哈哈,小伙伴们又来学习啦~今天我将给大家介绍《如何根据物品数量和名称对商品价格数组进行分组排序?》,这篇文章主要会讲到等等知识点,不知道大家对其都有多少了解,下面我们就一起来看一吧!当然,非常希望大家能多多评论,给出合理的建议,我们一起学习,一起进步!

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

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

文中关于的知识介绍,希望对你的学习有所帮助!若是受益匪浅,那就动动鼠标收藏这篇《如何根据物品数量和名称对商品价格数组进行分组排序?》文章吧,也可关注golang学习网公众号了解相关技术文章。

相关阅读
更多>
最新阅读
更多>
课程推荐
更多>