Reputation: 2867
I have a javascript object like this. Given a number n
, how do I get n
keys with smallest and largest values?
let obj = {
"1632": 45,
"1856": 12,
"1848": 56,
"1548": 34,
"1843": 88,
"1451": 55,
"4518": 98,
"1818": 23,
"3458": 45,
"1332": 634,
"4434": 33
};
Upvotes: 1
Views: 100
Reputation: 35242
You could sort
the key-value pair array returned by Object.entries
and get the first n
keys like this:
let obj={"1632":45,"1856":12,"1848":56,"1548":34,"1843":88,"1451":55,"4518":98,"1818":23,"3458":45,"1332":634,"4434":33};
const n = 5;
const smallestNKeys = Object.entries(obj)
.sort((a, b) => a[1] - b[1])
.slice(0, n)
.map(a => a[0])
console.log(smallestNKeys)
Or loop through the keys
to avoid an additional map
let obj={"1632":45,"1856":12,"1848":56,"1548":34,"1843":88,"1451":55,"4518":98,"1818":23,"3458":45,"1332":634,"4434":33};
const n = 5;
const smallestNKeys = Object.keys(obj)
.sort((a, b) => obj[a] - obj[b])
.slice(0, n)
console.log(smallestNKeys)
Since you mentioned smallest OR largest, you can create a function which accepts the order
parameter. Then based on the parameter, you can multiply 1 or -1 in the sort
's compareFunction callback.
let obj={"1632":45,"1856":12,"1848":56,"1548":34,"1843":88,"1451":55,"4518":98,"1818":23,"3458":45,"1332":634,"4434":33};
getSortedKeys = (obj, n, order) => {
const multiplier = order === "asc" ? 1 : -1;
return Object.keys(obj)
.sort((a, b) => multiplier * (obj[a] - obj[b]))
.slice(0, n)
}
console.log(getSortedKeys(obj, 3, "desc"))
console.log(getSortedKeys(obj, 5, "asc"))
Upvotes: 3
Reputation: 37755
You can use Object.entries, sort and reduce
let obj = { "1632": 45, "1856": 12, "1848": 56, "1548": 34, "1843": 88, "1451": 55, "4518": 98, "1818": 23, "3458": 45, "1332": 634, "4434": 33 };
let findNkeys =
(input,n) => Object.entries(input)
.sort(([,A],[,B])=>A-B)
.reduce((op,[key],index)=>( index < n ? op.push(key) : op, op),[])
console.log(findNkeys(obj,2))
Upvotes: 0
Reputation: 2867
Here is the code for finding n keys with smallest values. To change it to largest keys change < in third line to >
const smallestkeys = (obj, n = 1) =>
Object.keys(obj).reduce((keyArr, k, i) =>
(!i || obj[k] < obj[keyArr[keyArr.length - 1]])
? [k, ...keyArr].slice(0, n).sort((a, b) => obj[a] - obj[b])
: keyArr
, []);
Upvotes: 0