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;
}, {});
}
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.
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:
Note: In case of an object the key must be provided so we first checks if it is. If so, we use the specified property for comparison. Otherwise, we compare the entire value (in case of a object without the key parameter it will compare pointers which leads to random results).
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 }
Note: we could easily change our function to handle other comparators, like finding the maximum value (>=) or the value that meets a certain condition.
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.
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: