1const simpleArray = [3, 5, 7, 15];
2const objectArray = [{ name: 'John' }, { name: 'Emma' }]
3
4console.log( simpleArray.find(e => e === 7) )
5// expected output 7
6
7console.log( simpleArray.find(e => e === 10) )
8// expected output undefined
9
10console.log( objectArray.find(e => e.name === 'John') )
11// expected output { name: 'John' }
1const inventory = [
2 {name: 'apples', quantity: 2},
3 {name: 'cherries', quantity: 8}
4 {name: 'bananas', quantity: 0},
5 {name: 'cherries', quantity: 5}
6 {name: 'cherries', quantity: 15}
7
8];
9
10const result = inventory.find( ({ name }) => name === 'cherries' );
11
12console.log(result) // { name: 'cherries', quantity: 5 }
1const array1 = [5, 12, 8, 130, 44];
2
3const found = array1.find(element => element > 10);
4
5console.log(found);
6// expected output: 12
1const inventory = [
2 {id: 23, quantity: 2},
3 {id: '24', quantity: 0},
4 {id: 25, quantity: 5}
5];
6// Check type and value using ===
7const result = inventory.find( ({ id }) => id === 23 );
8// Check only value using ==
9const result = inventory.find( ({ id }) => id == 24 );
1const inventory = [
2 {name: 'apples', quantity: 2},
3 {name: 'bananas', quantity: 0},
4 {name: 'cherries', quantity: 5}
5];
6
7function findCherries(fruit) {
8 return fruit.name === 'cherries';
9}
10
11inventory.find(findCherries); // { name: 'cherries', quantity: 5 }
12
13/* OR */
14 inventory.filter(x => x.name === 'bananas')[0]; // { name: 'bananas', quantity:0}
15
16/* OR */
17
18inventory.find(e => e.name === 'apples'); // { name: 'apples', quantity: 2 }
1var ages = [3, 10, 18, 20];
2
3function checkAdult(age) {
4 return age >= 18;
5}
6/* find() runs the input function agenst all array components
7 till the function returns a value
8*/
9ages.find(checkAdult);
10