Finding the smallest value in a JSON object in JavaScript


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

Updated on: 20-Nov-2020

640 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements