Created
December 1, 2023 19:17
-
-
Save ChathuraGH/010d2b9997e2d332c4aed9d4122dde39 to your computer and use it in GitHub Desktop.
Object.entries(dict).sort
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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