Activity › Forums › Salesforce® Discussions › what are the use cases of find and findindex js array methods in Salesforce?
-
what are the use cases of find and findindex js array methods in Salesforce?
Posted by Yogesh on November 12, 2019 at 9:13 AMi need to know when to use these methods in a js function.
Prachi replied 6 years, 6 months ago 2 Members · 1 Reply -
1 Reply
-
Hi Yogesh,
1.With findIndex() method we return the index of the first element in the array that satisfies the provided testing function.
use case of findIndex()-
-> FIND INDEX OF A FRUIT WITH FINDINDEX()
Firstly we will find the index of a fruit inside a fruit array using arrow functions:const fruits = [“apple”, “banana”, “cantaloupe”, “blueberries”, “grapefruit”];<br/>// find the index of the “blueberries”
const index = fruits.findIndex(fruit => fruit === “blueberries”);
console.log(index); // 3
console.log(fruits[index]); // blueberries
As a use case this is good when we want to find the first item that matches our condition when it exists in the array. Otherwise, it returns -1, indicating no element passed the test.->FIND THE ODD ELEMENT WITH FINDINDEX()
Also this is another example to find the odd element inside an array:let arr = [2, 4, 6, 8, 9, 10, 12];
// create the function to check if the item is odd
function isOdd(i) {<br/> return i % 2 !== 0;<br/>}<br/>//return the index
arr.findIndex(isOdd);2.Using find() method we return the value of the first element in the array **that satisfies the provided testing function.
Use case of find()-
->FIND THE FRUIT OBJECT WITH FIND()
const inventory = [
{name: ‘apples’, quantity: 2},
{name: ‘bananas’, quantity: 0},
{name: ‘cherries’, quantity: 5}
];
// look for fruit with the name property of “cherries”
const result = inventory.find( fruit => fruit.name === ‘cherries’ );console.log(result) // { name: ‘cherries’, quantity: 5 }
Above example shows how we can find an object inside an array using find() method looking for an object property( name here).->FIND THE ODD ELEMENT WITH FIND() THIS TIME
let arr = [2, 4, 6, 8, 9, 10, 12];
// create the function to check if the item is odd
function isOdd(i) {<br/> return i % 2 !== 0;<br/>}<br/>//return the number this time
arr.find(isOdd);Similar function being passed to find(0 but this time we have found the actual number.
Thanks.
Log In to reply.