比较多维数组并在 JavaScript 中找到 min/max 个值

Compare multidimensional arrays and find min/max values in JavaScript

在我的 JavaScript 游戏中,我将分数保存在多维数组中(在本地存储中)。

我正在保存一个 themeID,一个已播放主题的标识符。此外,我正在保存游戏设置(piecesshapesSquare)和游戏的 duration

我现在需要比较分数以找到每个设置的最佳分数(=高分)。在这种情况下,最好的分数意味着最低的持续时间值(请随意忽略持续时间的格式,因为我知道如何比较时间戳,只需将其视为常规数字即可)。

对我来说关键点是只比较不同的设置,然后找到最低的持续时间值。我不需要整个阵列的最低持续时间,但需要为每个设置找到它。这意味着我需要找出 themeIDpiecesshapesSquare 的相同位置以比较分数。如果 piecesshapesSquare 不同,则此 themeID.

的高分应该不同

对我来说最完美的结果是我为每个主题设置一个数组并设置 "best" 分数。

数组如下所示:

let scores = [
  {
    "themeID": 1,
    "pieces": 10,
    "shapesSquare": true,
    "duration": "00:01:00"
  },
  {
    "themeID": 1,
    "pieces": 10,
    "shapesSquare": true,
    "duration": "00:01:30"
  },
  {
    "themeID": 4,
    "pieces": 20,
    "shapesSquare": false,
    "duration": "00:04:00"
  },
  {
    "themeID": 4,
    "pieces": 30,
    "shapesSquare": true,
    "duration": "00:03:20"
  }
]

顺便说一句,我对 scores 数组非常灵活,因为它是我自己创建的,所以如果您对更改结构(以便更容易迭代)有任何建议,请随时告诉我。

提前感谢您的帮助!

我会尝试类似的方法:

const minMaxDurationMap = new Map();
for (const score of scores) {
    const key = JSON.stringify([score.themeID,score.pieces,score.shapesSquare]);
    const minMax = minMaxDurationMap.get(key);
    if (minMax) {
        if (score.duration < minMax.min) minMax.min = score.duration;
        else if (score.duration > minMax.max) minMax.max = score.duration;
    } else {
        minMaxDurationMap.set(key, { min: score.duration, max: score.duration });
    }
}

顺便说一句,我认为您应该将持续时间存储为数字(秒或毫秒)而不是字符串。

我对我的解决方案的密钥生成不满意,但我想不出更好的办法。