xxxxxxxxxx
const myArray = ["sun","moon","earth"];
const lookingFor = "earth"
console.log(myArray.find(planet => { return planet === lookingFor })
// expected output: earth
xxxxxxxxxx
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 }
xxxxxxxxxx
const array1 = [5, 12, 8, 130, 44];
const found = array1.find(element => element > 10);
console.log(found);
// expected output: 12
xxxxxxxxxx
const array1 = [5, 12, 8, 130, 44];
const found = array1.find(element => element > 10);
console.log(found);
// expected output: 12
xxxxxxxxxx
var ages = [3, 10, 18, 20];
function checkAdult(age) {
return age >= 18;
}
/* find() runs the input function agenst all array components
till the function returns a value
*/
ages.find(checkAdult);
xxxxxxxxxx
const users = [
{id: 1, name: "test user 1"},
{id: 2, name: "test user 2"}
];
const found = users.find(user => user.id === 1);
const notFound = users.find(user => user.id === 99)
console.log(found) // { id: 1, name: 'test user 1' }
console.log(notFound) // undefined
xxxxxxxxxx
function include(arr, obj) {
for (var i = 0; i < arr.length; i++) {
if (arr[i] == obj) return true;
}
}
console.log(include([1, 2, 3, 4], 3)); // true
console.log(include([1, 2, 3, 4], 6)); // undefined
Run code snippet
xxxxxxxxxx
const numbers = [4, 9, 16, 25, 29];
let first = numbers.find(myFunction);
function myFunction(value, index, array) {
return value > 18;
}
xxxxxxxxxx
//find is higher oder function that return only if condition is true
const names= ["Shirshak","SabTech","Kdc"]
const searchName = names.find(function(name){
return names.inclues("Shirshak")
})
xxxxxxxxxx
const array1 = [5, 12, 50, 130, 44];
const isLarger = (element) => element > 45 ;
const found = array1.find(isLarger);
console.log(found);
//output 50