js sort array by key 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));
});
}
Example 3: javascript sort by id
elems.sort((a, b) => a.id - b.id);