sort array by value of a key in js code example
Example 1: javascript sort array of objects by key value
arr.sort((x, y) => x.distance - y.distance);
Example 2: array sort by key javascript
function sortByKey(array, key) {
return array.sort((a, b) => {
let x = a[key];
let y = b[key];
return ((x < y) ? -1 : ((x > y) ? 1 : 0));
});
}