Get the Min/Max Values in a Map or a Set in JavaScript


JavaScript Maps and Sets are crucial data structures, allowing efficient retreival (O(1)) using unique keys. In this exploration, we delve into methods to find the minimum and maximum values in both Maps and Sets. Since both these data structures are unsorted and unordered, these techniques can be handy.

When working with Sets in JavaScript, efficiently accessing the first element is crucial. Let’s explore the various methods to do so.


JavaScript Map: Unordered Key-Value Pairs

Getting Min/Max Values in a JavaScript Map

Using Spread Syntax and Math Methods

We can use the spread syntax and Math methods. The spread syntax unpacks the Map’s values into separate arguments for the Math.min() and Math.max() functions, allowing us to efficiently identify the minimum and maximum values.

JavaScript
const map1 = new Map([
  ['num1', 3],
  ['num2', 5],
  ['num3', 8],
]);

const min = Math.min(...map1.values());
const max = Math.max(...map1.values());

console.log(min); // πŸ‘‰οΈ 3
console.log(max); // πŸ‘‰οΈ 8

Using Array.reduce() Method

For a more comprehensive approach that includes keys, we use the Array.reduce() method. This method iterates over the Map’s entries, comparing values to determine the minimum and maximum elements.

JavaScript
const map1 = new Map([
  ['num1', 3],
  ['num2', 5],
  ['num3', 8],
]);

const max = [...map1.entries()].reduce((accumulator, element) => {
  return element[1] > accumulator[1] ? element : accumulator;
});

const min = [...map1.entries()].reduce((accumulator, element) => {
  return element[1] < accumulator[1] ? element : accumulator;
});

console.log(max); // πŸ‘‰οΈ [ 'num3', 8 ]
console.log(min); // πŸ‘‰οΈ [ 'num1', 3 ]

JavaScript Set: Distinct Values in an Orderless Set

In contrast, a JavaScript Set is an unordered collection of distinct values. Unlike Maps, Sets do not store key-value pairs; they focus solely on unique values. Sets are valuable when dealing with lists of items where uniqueness is crucial, providing a streamlined approach to handle iterable collections without the need for explicit keys.

Lets see how to get minimum and maximum elements of Set (using their iterable nature).

Using Spread Syntax and Math Methods (Set)

To obtain min and max values from a Set, we again utilize the spread syntax with Math methods. Sets’ iterable nature allows for a concise representation of the minimum and maximum values.

JavaScript
const set1 = new Set([3, 5, 8]);

const min = Math.min(...set1);
const max = Math.max(...set1);

console.log(min); // πŸ‘‰οΈ 3
console.log(max); // πŸ‘‰οΈ 8

Defining a Reusable Function

JavaScriptFor enhanced readability and reusability, a function named setMinMax is introduced. This function takes a Set as a parameter and returns an object containing the minimum and maximum values. Just trying to keep the code DRY (Dont Repeat Yourself).

JavaScript
function setMinMax(set) {
  const min = Math.min(...set);
  const max = Math.max(...set);
  return { min, max };
}

const set1 = new Set([3, 5, 8]);
const result = setMinMax(set1);

console.log(result); // πŸ‘‰οΈ { min: 3, max: 8 }

Practice Problem: Find Top Scorer

In spirit of Test Driven Development, (😁), lets test your understanding with a problem.

Given a Map named scoreMap containing student names as keys and their scores as values, find and return the name of the top scorer. This example introduces the practical application of Maps, demonstrating how to iterate over entries to identify the student with the highest score.

JavaScript
function findTopScorer(scoreMap) {
  // > > > πŸ‘‰  πŸ‘ˆ < < <
}

const scores = new Map([
  ['Alice', 95],
  ['Bob', 88],
  ['Charlie', 92],
  // Add more entries as needed
]);

console.log(findTopScorer(scores)); 
// Expected output: The name of the top scorer
Please attempt before seeing the Answer:
JavaScript
function findTopScorer(scoreMap) {
  let topScorer = '';
  let highestScore = -1;

  for (const [name, score] of scoreMap) {
    if (score > highestScore) {
      highestScore = score;
      topScorer = name;
    }
  }

  return topScorer;
}

Conclusion:

JavaScript Maps and Sets offer versatile solutions for handling key-value pairs and unique-valued, iterable collections. Leveraging spread syntax, Math methods, and functions like reduce enhances our ability to retrieve valuable information from these data structures. Whether dealing with Maps or Sets, understanding their behaviors allows us to optimize our code for various scenarios. Happy coding! πŸš€

Scroll to Top