'find max elements of an array in JS, elements might be same

I know there are a lot of questions about how to get max from an array, but they all have unique elements. my scenario is different, for example:

find_multiple_max([10,20,30,30])

will return

[30, 30]

I found a solution and it works:

function find_multiple_max(arr) {
    var max;
    arr = arr.sort((a,b) => b-a)
            .filter(e => {
                if (!max) {
                    max = e;
                    return true;
                } 
                return (e == max);
            });
    console.log(arr);
    return arr;
}

I was still wondering if any simpler answer exists.



Solution 1:[1]

You can still use Math.max which will return the maximum element from the array and then use filter to get an array

function find_multiple_max(arr) {
  let maxElem = Math.max(...arr);
  return arr.filter(item => item == maxElem)
}
console.log(find_multiple_max([10, 20, 30, 30]))

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 brk