This function sorts an array of objects based on a given key.
JavaScript:
let sortByKey = (arr, key) => arr.sort((a, b) => a[key] > b[key] ? 1 : -1);
// Example
console.log(sortByKey([{name: 'John', age: 23}, {name: 'Jane', age: 21}, {name: 'Oliver', age: 25}], 'age')); // [{name: 'Jane', age: 21}, {name: 'John', age: 23}, {name: 'Oliver', age: 25}]
console.log(sortByKey([{name: 'John', age: 23}, {name: 'Jane', age: 21}, {name: 'Oliver', age: 25}], 'name')); // [{name: 'Jane', age: 21}, {name: 'John', age: 23}, {name: 'Oliver', age: 25}]
TypeScript:
let sortByKey = (arr: T[], key: keyof T): T[] => arr.sort((a, b) => a[key] > b[key] ? 1 : -1);
// Example
console.log(sortByKey([{name: 'John', age: 23}, {name: 'Jane', age: 21}, {name: 'Oliver', age: 25}], 'age')); // [{name: 'Jane', age: 21}, {name: 'John', age: 23}, {name: 'Oliver', age: 25}]
console.log(sortByKey([{name: 'John', age: 23}, {name: 'Jane', age: 21}, {name: 'Oliver', age: 25}], 'name')); // [{name: 'Jane', age: 21}, {name: 'John', age: 23}, {name: 'Oliver', age: 25}]