【问题标题】:How do you sort an array by only using specific elements?如何仅使用特定元素对数组进行排序?
【发布时间】:2021-09-23 16:02:08
【问题描述】:

我将数组用作临时库存(作为游戏的一部分)。有 itemsvalues,每个都是一个 string。他们总是被跟踪。

价值或数量决定了您拥有该物品的多少。

例如:inventoryArray = ['bananas', '5', 'berries', '8', 'apples','3']

在上面的示例中,您将有一个 香蕉,其数量为 5

我的目标是按数量对数组进行排序。所以一个函数可以返回['berries', '8','bananas', '5' 'apples','3']

谢谢!

【问题讨论】:

  • 您绝对应该考虑使用键/值对而不是数组的数据结构。一个简单的对象可以很好地完成您的操作。 inventoryArray = { 香蕉:5,浆果:8,苹果:3 }
  • 使用对象数组:inventoryArray = [{ name: "bananas", count: 5 }, { ... }] 像这样:jsfiddle.net/0rjfhnv2
  • 基于对象的清单可以解决问题。感谢您的快速回复!
  • @ChrisG 您的回答完美无缺。谢谢!

标签: javascript node.js arrays


【解决方案1】:

正如其他人所指出的,这似乎是 A Bad Idea™,您确实应该考虑使用更合适的数据结构。

话虽如此,还是有办法的。

在下面的 sn-p 中,我首先通过 reduce 将数组转换为对象,因此您最终会得到这样的结构(您应该首先考虑使用):

{
  bananas: 5,
  berries: 8,
  apples: 3
}

然后我对该对象的entries 进行排序,生成一个排序后的数组对:

[
  ['apples', 3],
  ['bananas', 5],
  ['berries', 8],
]

最后,flattening 该数组会产生您想要的结果:

['apples', 3, 'bananas', 5, 'berries', 8]

再次,我同意上述 cmets 的建议,即这需要更合适的数据结构,但如果您出于某种原因必须这样做,您可以这样做。

const inventoryArray = ['bananas', '5', 'berries', '8', 'apples','3']

const quantities = inventoryArray.reduce((acc, item, index, arr) => {
  // skip odd indices (the quantities)
  if (index % 2 === 1) {
    return acc;
  }
  
  // add the product and qty (index + 1) to the result
  return {
    ...acc,
    [item]: Number(arr[index + 1])
  }
}, {});

// sort the key value pairs
const arr = Object.entries(quantities).sort(([, qtyA], [, qtyB]) => qtyA - qtyB);

console.log(arr.flat());

【讨论】:

    猜你喜欢
    • 2012-08-15
    • 1970-01-01
    • 1970-01-01
    • 2011-06-15
    • 2015-06-28
    • 1970-01-01
    • 1970-01-01
    • 2010-10-22
    • 1970-01-01
    相关资源
    最近更新 更多