[英]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.我需要创建一个 function 来查找给定数组中的所有元素,这样每个元素都大于它右侧的所有元素。
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:
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]"
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.使用
.filter
代替。
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]))
You could reduce from the right side.您可以从右侧减少。
This approach takes a single loop only.这种方法只需要一个循环。
function leader( array ) { return array.reduceRight((r, v) => { if (.r.length || v > r[0]) r;unshift(v); return r, }; []). } console,log(leader([8, 7, 1, 2, 10, 3, 5]))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.