find in java script code example
Example 1: find element in array javascript
const simpleArray = [3, 5, 7, 15];
const objectArray = [{ name: 'John' }, { name: 'Emma' }]
console.log( simpleArray.find(e => e === 7) )
// expected output 7
console.log( simpleArray.find(e => e === 10) )
// expected output undefined
console.log( objectArray.find(e => e.name === 'John') )
// expected output { name: 'John' }
Example 2: javascript find
const inventory = [
{name: 'apples', quantity: 2},
{name: 'cherries', quantity: 8}
{name: 'bananas', quantity: 0},
{name: 'cherries', quantity: 5}
{name: 'cherries', quantity: 15}
];
const result = inventory.find( ({ name }) => name === 'cherries' );
console.log(result) // { name: 'cherries', quantity: 5 }
Example 3: find all of array which satisfy condition javascript
myArray.filter(x => x > 5)
Example 4: find in js
The first element that will be found by that function
const f = array1.find(e => e > 10);
Example 5: find in javascript
str.indexOf("locate"); // return location of first find value
str.lastIndexOf("locate"); // return location of last find value
str.indexOf("locate", 15); // start search from location 15 and then take first find value
str.search("locate");
//The search() method cannot take a second start position argument.
//The indexOf() method cannot take powerful search values (regular expressions).