You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何按指定元素对数组排序 实现游戏背包数组按物品数量排序

实现思路

  1. 先把原一维数组按顺序两两拆分,得到「物品名+数量字符串」的分组结构
  2. 对分组按数量的数值大小做降序排序
  3. 把排序后的分组重新展开为一维数组,即可得到预期结果

代码实现(JavaScript)

function sortInventoryByCount(inventoryArray) {
  // 两两分组
  const groupedInventory = [];
  for (let i = 0; i < inventoryArray.length; i += 2) {
    groupedInventory.push([inventoryArray[i], inventoryArray[i + 1]]);
  }
  // 按数量降序排序,注意要把字符串格式的数量转成数字比较
  groupedInventory.sort((a, b) => Number(b[1]) - Number(a[1]));
  // 扁平化回一维数组返回
  return groupedInventory.flat();
}

测试效果

用你给出的示例输入测试:

const inventoryArray = ['bananas', '5', 'berries', '8', 'apples','3'];
console.log(sortInventoryByCount(inventoryArray));
// 输出结果:['berries', '8', 'bananas', '5', 'apples', '3']

注意说明

你给出的预期返回结果里'bananas', '5' 'apples'部分漏了逗号属于笔误,上述代码输出的是符合语法的正确数组。另外因为你提到物品和数量总是成对出现,所以代码无需额外处理数组长度为奇数的异常场景,如有需要可自行添加边界判断。

内容的提问来源于stack exchange,提问作者rbg12

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 20:09:03