简体   繁体   English

如何找到从数组末尾开始的数组元素?

[英]How can I find an array element starting from the end of the array?

JavaScript has array methods like indexOf and find for getting the first element in the array that matches the criteria. JavaScript具有数组方法,如indexOffind用于获取数组中符合条件的第一个元素。 The counterpart to indexOf would be lastIndexOf , which searches starting from the end of the array instead. indexOf对应的对象是lastIndexOf ,它从数组的末尾开始搜索。 I'm wondering now if there is a counterpart to find that starts from the end of the array, like a native implementation of Ramda's findLast . 现在我想知道如果有一个对口find从数组的末尾开始,像本地实现的Ramda的findLast

I would prefer to use neither array.slice().reverse().find() due to performance costs nor a for loop as it is verbose and not in the spirit of functional programming 由于性能成本或for循环的原因,我array.slice().reverse().find()使用array.slice().reverse().find()因为它很冗长,不符合函数式编程的精神

No there is not, but you can polyfill it easily: 没有,但您可以轻松地对其进行填充:

 Array.prototype.findLast = function(fn) {
  for(let i = this.length - 1; i >= 0; i--) 
    if(fn( this[i], i, this )) return this[i];
  return null;
 };



console.log([5,4,3,2,1].findLast(el => el > 3));

You can use reduceRight , which is in the spirit of functional programming. 您可以使用reduceRight ,这是函数式编程的精神。 However, it's not as easy ( but possible ) to return early upon finding a match as it is in a for loop: 但是,找到匹配项并不像for循环中那样容易( 但可能 )早返回:

 const lastIndexOf = (needle, haystack) => haystack.reduceRight((a, e, i) => a >= 0 ? a : e === needle ? i : -1 , -1) ; const arr = [1,4,3,5,5,4,5]; console.log(lastIndexOf(4, arr)); console.log(lastIndexOf(2, arr)); 

There's also recursion, which has similar efficiency problems (stack frame overhead, no instantaneous early return, having to write a helper or extra conditionals, you'll blow the stack if the array is large...): 还有一个递归,它也有类似的效率问题(堆栈帧开销,没有即时的提前返回,必须编写一个辅助函数或额外的条件,如果数组很大,您将把堆栈炸掉……):

 const lastIndexOf = (needle, haystack, idx) => lastIndexOfHelper(needle, haystack, haystack.length - 1) ; const lastIndexOfHelper = (needle, haystack, idx) => idx < 0 || haystack[idx] === needle ? idx : lastIndexOfHelper(needle, haystack, idx - 1) ; const arr = [1,4,3,5,5,4,5]; console.log(lastIndexOf(4, arr)); console.log(lastIndexOf(2, arr)); 

Lodash has a _.findLastIndex() method which interates over a collection from right to left. Lodash有一个_.findLastIndex()方法,该方法从右到左遍历一个集合。 https://lodash.com/docs/4.17.10#findLastIndex https://lodash.com/docs/4.17.10#findLastIndex

Not sure as to its performance though 虽然不确定其性能

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM