In this article, you will learn about javascript Array built-in method Array.prototype.findLast(). How does this method work in javascript?
This Array.prototype.findLast()
method returns the value of the last element from the provided array which passes the test that is implemented by the callback()
function. If no elements pass the test, it returns undefined
.
array.findLast(callback(element [, index [, array]]) [,thisParameter]);
This method takes 2 Parameters as given below:
this
to be used while executing the callback function.The findLast()
method does not execute the callback function for empty elements. And it does not change the original array.
Here are some examples of Array.prototype.findLast() method:
//find the last element in an array that is greater than 30
console.log([12, 5, 8, 130, 44].findLast(x => x > 30));
// output => 44
//find the last element in an array that is greater than 130
console.log([12, 5, 8, 130, 44].findLast(x => x > 130));
// output => undefined
let cities = [
{name: 'Los Angeles', population: 3792621},
{name: 'New York', population: 8175133},
{name: 'Chicago', population: 2695598},
{name: 'Houston', population: 2099451},
{name: 'Philadelphia', population: 1526006}
];
//find the last element of the city where the population is greater than 5000000
let metroCities = cities.findLast(city => city.population > 5000000);
console.log(metroCities);
//----output----
/*
{
"name": "New York",
"population": 8175133
}
*/
I hope this article will help you to understand the javascript Array built-in method Array.prototype.findLast().
Share your valuable feedback, please post your comment at the bottom of this article. Thank you!
Comments