Many time we need to traverse the array data while building the application. Fortunately, JavaScript provides many array functions to do that but use case of these functions are different. Here in the below description, we'll discuss the ES6 array functions find() and filter().
If we only wanted to return the first matching element in the array: We use find() for this. .find() will look and stop after the first match. Let me explain with an example:
Let say we have a products array and we wanted to find the price of TV in below example:
1
2
3
|
var products = [{name:'Bowl',price:1200},{name:'TV',price:15000},{name:'Table',price:2500},{name:'TV',price:14000}];
var result = products.find((product)=>{ return product.name==='TV'});
console.log(result);
|
The output of the above script will be:
1
|
{name: "TV", price: 15000}
|
Now If we run filter() function in the same case then it will return the array of objects whose name is TV. .filter() will continue searching through the entire array.
1
2
3
|
var products = [{name:'Bowl',price:1200},{name:'TV',price:15000},{name:'Table',price:2500},{name:'TV',price:14000}];
var result = products.filter((product)=>{ return product.name==='TV'});
console.log(result);
|
The output of the above script will be:
1
|
[{name: "TV", price: 15000},{name: "TV", price: 14000}]
|
find() and filter() are only used when we wanted to return the matching results and use them but if we just wanted to check the existence of matching result, in that case, we can use some() and every() ES6 functions. ...