This function finds the smallest number in an array of objects, based on a specified key.
JavaScript:
let minItemByKey = (arr, key) => arr.reduce((min, obj) => obj[key] < min[key] ? obj : min);
// Example
console.log(minItemByKey([{id: 1, value: 10}, {id: 2, value: 5}, {id: 3, value: 20}], 'value')); // {id: 2, value: 5}
console.log(minItemByKey([{name: 'a', age: 20}, {name: 'b', age: 15}, {name: 'c', age: 25}], 'age')); // {name: 'b', age: 15}
TypeScript:
let minItemByKey = (arr: T[], key: string): T => arr.reduce((min, obj) => obj[key] < min[key] ? obj : min);
// Example
console.log(minItemByKey([{id: 1, value: 10}, {id: 2, value: 5}, {id: 3, value: 20}], 'value')); // {id: 2, value: 5}
console.log(minItemByKey([{name: 'a', age: 20}, {name: 'b', age: 15}, {name: 'c', age: 25}], 'age')); // {name: 'b', age: 15}