Skip to content

What am I missing in my function (return an array of element that is greater than the element to its right)?

I need to create a function that finds all elements in the given array, such that each element is greater than all elements to the right of it.

Examples

leader([2, 3, 20, 15, 8, 3]) ➞ [20, 15, 8, 3]

leader([2, 3, 20, 15, 8, 25, 3]) ➞ [25, 3]

Here is my function :

function leader( array ) {
  return array.slice(array.indexOf(Math.max(...array)))
  }
console.log(leader([8, 7, 1, 2, 10, 3, 5]))

The test that makes me fail is when this array is called:

leader([8, 7, 1, 2, 10, 3, 5]) // "Expected : [10,5], Received : [10,3,5]"

Answer

Just finding the index of the max element isn’t enough, because the elements that come after the max element may not be in decreasing order. Use .filter instead.

function leader( array ) {
  return array.filter(
    (num, i) => array.slice(i + 1).every(
      otherNum => num > otherNum
    )
  );
}
console.log(leader([8, 7, 1, 2, 10, 3, 5]))