1// To find a specific object in an array of objects
2myObj = myArrayOfObjects.find(obj => obj.prop === 'something');
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 }
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
1const myArray = ["sun","moon","earth"];
2const lookingFor = "earth"
3
4console.log(myArray.find(planet => { return planet === lookingFor })
5// expected output: earth