Search code examples
javascriptarraysmultidimensional-arraycomparison

Compare multidimensional arrays and find min/max values in JavaScript


In my JavaScript game I'm saving scores in a multidimensional array (in a local storage).

I'm saving a themeID, an identifier for the theme which has been played. Furthermore I'm saving the game settings (pieces and shapesSquare) and the duration of the game.

I now need to compare the scores to find the best score for each setting (= highscore). Best score in this case means the lowest duration value (feel free to ignore the format of the duration because I know how to compare timestamps, just see it as regular numbers).

The crucial point for me is to compare different settings only and then find the lowest duration value. I don't need just the lowest duration of the whole array but need to find it for each settings. That means I need to find out where themeID, pieces and shapesSquare are identical to compare the score. If pieces or shapesSquare are different, then this should be a different highscore for this themeID.

The perfect result for me would be an array where I have for each theme and setting the "best" score.

The array looks like:

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

By the way I'm quite flexible with the scores array because I create it by myself, so if you have any suggestions in changing the structure (to make it easier to iterate), feel free to tell me.

Thank you in advance for any help!


Solution

  • I'd try something like:

    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 });
        }
    }
    

    As an aside, I think you should store your duration in a number (seconds or milliseconds) instead of a string.

    I'm not happy with the key generation of my solution, but I wasn't able to come up with anything better.