Get key with minimum value
To get only the minimum number you can use Math.min(...Object.entries(arr).map(o => o[1]))
:
const arr = {lst1: 300, lst2: 381, lst3: 4, lst4: 4, lst5: 49};
const lowestValue = Math.min(...Object.entries(arr).map(o => o[1]));
console.log(lowestValue);
And to get the object with the minimum value you can use Object.entries(arr).reduce((a, [k, v]) => a[Object.keys(a)[0]] < v ? a : {[k]: v}, {})
:
const arr = {lst1: 300, lst2: 381, lst3: 4, lst4: 4, lst5: 49};
const lowestObj = Object.entries(arr).reduce((a, [k, v]) => a[Object.keys(a)[0]] < v ? a : {[k]: v}, {});
console.log(lowestObj);
There are many ways to approach your problem, but here is one simple alternative way to do it. Basically, it is a brute force way of doing things, whereby you iterate through every property to check for the value.
const obj = {lst1: 300, lst2: 381, lst3: 4, lst4: 4, lst5: 49};
const getSmallest = function (object) {
let smallestValue = Number.MAX_VALUE;
let selectedKey = '';
for (let key in object) {
if (object[key] < smallestValue) {
smallestValue = object[key];
selectedKey = key;
}
};
console.log(selectedKey, smallestValue)
return `The lowest value is ${smallestValue} from ${selectedKey}`;
};
getSmallest(obj);
There are several ways to arrive at what you want. Please see the following methods:
const obj = { lst1: 300, lst2: 381, lst3: 4, lst4: 4, lst5: 49 }
const values = Object.values(obj)
const lowest = Math.min.apply(null, values)
// Using Object.keys(), Object.values() and findIndex()
const keys = Object.keys(obj)
const indexOfLowest = values.findIndex(function (x) { return x === lowest })
console.log(`The lowest value is ${lowest} from ${keys[indexOfLowest]}`)
// OR Using Object.keys() and filter()
const key = Object.keys(obj).filter(function (x) { return obj[x] === lowest })[0]
console.log(`The lowest value is ${lowest} from ${key}`)
// OR Using Object.entries() and sort()
const [[lowestKey, lowestVal]] = Object.entries(obj).sort(function ([,valA], [,valB]) { return valA - valB });
console.log(`The lowest value is ${lowestVal} from ${lowestKey}`)
You can get the key and value using Object.entries
:
var arr = {
lst1: 300,
lst2: 381,
lst3: 4,
lst4: 4,
lst5: 49
};
function lowestValueAndKey(obj) {
var [lowestItems] = Object.entries(obj).sort(([ ,v1], [ ,v2]) => v1 - v2);
return `Lowest value is ${lowestItems[1]}, with a key of ${lowestItems[0]}`;
}
var lowest = lowestValueAndKey(arr);
console.log(lowest);