Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
sorted-iteratable-map: iterate with a for-loop over a JavaScript Map sorted by value attributes with a custom iterator using function* and yield*
// In the example: sort descending by 'activeUsers' attribute of the value object
var countries = new Map();
countries.set('DE', { name: 'Germany', activeUsers: 15000 });
countries.set('PL', { name: 'Poland', activeUsers: 13900 });
countries.set('UK', { name: 'United Kingdom', activeUsers: 14500 });
console.log('without iterator:');
for (let [key, info] of countries) {
console.log(key + ' - ' + info.name + ', ' + info.activeUsers);
}
// DE - Germany, 15000
// PL - Poland, 13900
// UK - United Kingdom, 14500
// *** Here comes the magic :) ***
countries[Symbol.iterator] = function* () {
yield* [...countries.entries()].sort((a, b) => b[1].activeUsers - a[1].activeUsers);
}
console.log('with custom iterator:');
for (let [key, info] of countries) {
console.log(key + ' - ' + info.name + ', ' + info.activeUsers);
}
// DE - Germany, 15000
// UK - United Kingdom, 14500
// PL - Poland, 13900
// Adding an antry to the map and check if sorting is still valid
countries.set('IT', { name: 'Italy', activeUsers: 14200 });
console.log('after adding an entry:');
for (let [key, info] of countries) {
console.log(key + ' - ' + info.name + ', ' + info.activeUsers);
}
// DE - Germany, 15000
// UK - United Kingdom, 14500
// IT - Italy, 14200
// PL - Poland, 13900
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment