Method underscore.js findLast ()

Does Underscore.js have a findLast() method or equivalent?

What is the best way to do .find() but return the last item that matches the collection?

+6
source share
3 answers

Flip the list and then use find :

 _.find(list.reverse(), iterator); 

Read the MDN for reverse documentation.


Unfortunately, a collection with an underscore can be either an array or an object. If your collection is an array, then you are in luck. You can use reverse . However, if it is an object, you will need to do this instead:

 _.find(Object.keys(list).reverse(), function (key) { return iterator(list[key], key, list); }); 

You can write findLast function for yourself:

 _.mixin({ findLast: function (list, iterator, context) { if (list instanceof Array) return _.find(list.slice(0).reverse(), iterator, context); else return _.find(Object.keys(list).reverse(), function (key) { return iterator.call(context, list[key], key, list); }); } }); 

Now you can use findLast , like any other underscore method.

+11
source

Using reverse , as suggested by @AaditMShah, is the easiest solution, but keep in mind that it manages the array in place . If you need to maintain the order of the elements, you will have to call reverse second time after you are done.

If you do not want to use reverse , you can

  • use Lodash instead of _.findLast
  • grab the appropriate code from Lodash, decompose into findLast and forEachRight and make your own findLast.

This is what it looks like if you only deal with arrays and don't care about objects:

 function findLast (array, callback, thisArg) { var index = array.length, last; callback = callback && typeof thisArg == 'undefined' ? callback : _.bind(callback, thisArg); while (index--) { if (callback(array[index], index, array) == true) { last = array[index]; break; } } return last; } 

(This works, but I did not test it properly. Therefore, for everyone who reads this, do some testing first and don't just copy the code.)

+3
source

Underscore 1.8.0 has implemented the findLastIndex method, which you can use to do this.

 var numbers = [1, 2, 3, 4]; var index = _.findLastIndex(numbers, isOddNumber); if (index > 0) { console.log(numbers[index]); } // returns 3 
+1
source

Source: https://habr.com/ru/post/953094/


All Articles