简体   繁体   English

我的 function 中缺少什么(返回一个大于其右侧元素的元素数组)?

[英]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.

相关问题 我缺少检查值是否与数组元素匹配并使用if / else打印警报的步骤 - What step am I missing to check if value matches array element and print an alert using if/else 我正在尝试使用 axios 和本地 json 文件通过单击按钮来呈现随机数组元素。 我错过了什么? - I am trying to render a random array element from a button click using axios and a local json file. What am I missing? 如果我处于其EventListener的函数中,如何获取Element - How can I get the Element if I am in the function of its EventListener 为什么我的 if 语句在只选择一个元素时返回大于 1? - Why does my if statement return greater than 1 when there's only one element selected? 返回一个大于其第二个值的新数组 - Return a new array that is greater than its 2nd value 我试图包装带有html元素的函数的返回值 - I am trying to wrap a return value from a function with an html element 为什么我的代码不过滤数组?我缺少什么? - why my code is not filtering the array?what am i missing? 我的功能没有触发。 我想念什么? - My function does not trigger. What am I missing? 我的第三个 JavaScript function 缺少什么? - What am I missing in my third JavaScript function? 我在使用正确的功能使元素变为红色吗? - I am I using the correct function for my element to turn red?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM