Skip to content

Instantly share code, notes, and snippets.

@ChathuraGH
Created December 1, 2023 19:17
Show Gist options
  • Save ChathuraGH/010d2b9997e2d332c4aed9d4122dde39 to your computer and use it in GitHub Desktop.
Save ChathuraGH/010d2b9997e2d332c4aed9d4122dde39 to your computer and use it in GitHub Desktop.
Object.entries(dict).sort
const k = 5;
const dict = {
"x" : 1,
"y" : 6,
"z" : 9,
"a" : 5,
"b" : 7,
"c" : 11,
"d" : 17,
"t" : 3
};
const compare = (a, b) => {
if(a > b) return -1;
if(a < b) return 1;
return 0
};
// Object.entries() to convert the dict to: [["x",3],["y",1],["z",2]]
let arr = Object.entries(dict).sort((a, b) => compare(a[1], b[1]));
// Getting the first k = 5 biggest elements:
let biggestElemsArr = [];
for(let j = 0; j < k; j++) {
biggestElemsArr.push(arr[j][0]);
}
console.log(biggestElemsArr);const k = 5;
const dict = {
"x" : 1,
"y" : 6,
"z" : 9,
"a" : 5,
"b" : 7,
"c" : 11,
"d" : 17,
"t" : 3
};
const compare = (a, b) => {
if(a > b) return -1;
if(a < b) return 1;
return 0
};
// Object.entries() to convert the dict to: [["x",3],["y",1],["z",2]]
let arr = Object.entries(dict).sort((a, b) => compare(a[1], b[1]));
// Getting the first k = 5 biggest elements:
let biggestElemsArr = [];
for(let j = 0; j < k; j++) {
biggestElemsArr.push(arr[j][0]);
}
console.log(biggestElemsArr);
//source
// https://stackoverflow.com/questions/25500316/sort-a-dictionary-by-value-in-javascript
// https://stackoverflow.com/a/75086038/13861187
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment