Finding the smallest value in a JSON object in JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented ProgrammingJSON

We are required to write a JavaScript function that takes in a JSON object as one and only argument.

The JSON object has string keys mapped to some numbers. Our function should traverse through the object, find and return the smallest value from the object.

Example

The code for this will be −

const obj = {
   "a": 4,
   "b": 2,
   "c": 5,
   "d": 1,
   "e": 3
};
const findSmallestValue = obj => {
   const smallest = Object.keys(obj).reduce((acc, val) => {
      return Math.min(acc, obj[val]);
   }, Infinity);
   return smallest;
}
console.log(findSmallestValue(obj));

Output

And the output in the console will be −

1
raja
Published on 20-Nov-2020 09:56:44
Advertisements