Logo

Programming-Idioms

History of Idiom 113 > diff from v22 to v23

Edit summary for version 23 by justafoo:
[JS] idiomatic, non-braindead version

Version 22

2019-09-26, 18:04:14

Version 23

2019-09-26, 18:11:45

Idiom #113 Iterate over map entries, ordered by values

Print each key k with its value x from an associative array mymap, in ascending order of x.
Note that multiple entries may exist for the same value x.

Idiom #113 Iterate over map entries, ordered by values

Print each key k with its value x from an associative array mymap, in ascending order of x.
Note that multiple entries may exist for the same value x.

Extra Keywords
traverse traversal
Extra Keywords
traverse traversal
Code
var sortable = []
for (let k in mymap) sortable.push([k, mymap[k]])
sortable.sort((a, b) => a[1] - b[1])

for (let val of sortable) console.log(`${val[0]}: ${val[1]}`)
Code
Object.entries(mymap)
  .sort((a, b) => a[1] - b[1])
  .forEach(([key, value]) => {
    console.log('key:', key, 'value:', value);
  });
Comments bubble
First turn the object into an array, then print it.