Array min value

Find the minimum value in a collection of primitives or objects


function findMin(data, key) {
  return data.reduce((accumulator, currentValue) => {
    const computedAccumulator = key 
      ? accumulator[key] 
      : accumulator;
    const computedCurrentValue = key 
      ? currentValue[key] 
      : currentValue;
    return computedAccumulator <= computedCurrentValue
      ? accumulator
      : currentValue;
  }, {});
}
js

Context

As a JavaScript developer doing some data analysis is frequent even more so when the task at hand is about finding the minimum or even the maximum value of a collection. The code snippet above is an implementation of a function that finds the minimum value in a collection of objects but it could be easily extended to support other comparator.

Usage

The function findMin() takes in two parameters data and key where data could be an array of primitive or objects. In case of objects, the key parameter becomes essential as it allows to specify which property to use for comparison. This function could be described in 2 simple steps:

  • First, the reduce() method is used to iterate over the array of values and reduce it to a single value, here, the minimum value found. In case of an object, the returned value is the object with the minimum value of the specified key parameter.
  • Second, inside the reduce() method, we compare the current value with the previous smallest value (starting with an empty object). If the current value has a lower value than the previous smallest value, it is replace by the current value.

Now, let's make this more concrete:

// Array of primitives
const randomNumbers = [124, "42", 99, 11];
findMin(randomNumbers); // 11

// Array of objects
const products = [
  { id: 1, name: "Beef", price: 10 },
  { id: 2, name: "Salmon", price: 20 },
  { id: 3, name: "Chicken", price: 5 },
];
findMin(products, "price"); 
// And tada 🎉
// { id: 3, name: "Chicken", price: 5 }
js

Conclusion

The findMin() function is a useful snippet for finding the minimum value in a collection of primitives or objects with a provided key. With its ability to compare objects by a specified property, it can be used in various scenarios to find the smallest value of a particular property in a collection and could be extended to use a custom comparator.

Last updated: February 21, 2023

⚡ Who am i to talk about this? ⚡

Honestly i am no one, i've just been coding for 3 years now and i like to document every solutions to every problem i encounter. Extracting as much code snippets and tutorials i can so that if i ever need it again i just have to pop back here and get a quick refresher.

Feel free to me through this learning journey by providing any feedback and if you wanna support me: