I want to find the largest element in an array. For example, finding the person with the highest salary. I can sort the array using a salary comparator, but it is inefficient. What is the simplest and best way to do this?
For reference, I can do this in Python as follows.
heapq.nlargest(1, [array_of_whatever], comparator)[0]
This is what I would do:
const maxBy = (comparator, array) => array.reduce((acc, val) => comparator(acc, val) > 0 ? acc : val); const employees = [ { name: "Alice", salary: 1000 } , { name: "Bob", salary: 2000 } , { name: "Charlie", salary: 1500 } ]; const salaryComparator = (a, b) => a.salary - b.salary; const max = maxBy(salaryComparator, employees); console.log(max);
Is this what you're looking for?
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.