// .find method only accepts a callback function
// and returns the first value for which the function is true.
const cities = [
"Orlando",
"Dubai",
"Denver",
"Edinburgh",
"Chennai",
"Accra",
"Denver",
"Eskisehir",
];
const findCity = (element) => {
return element === "Denver";
};
console.log(cities.find(findCity));
//Expected output is 4 (first instance of "Denver" in array)
const inventory = [
{name: 'apples', quantity: 2},
{name: 'bananas', quantity: 0},
{name: 'cherries', quantity: 5}
];
function isCherries(fruit) {
return fruit.name === 'cherries';
}
console.log(inventory.find(isCherries));
// { name: 'cherries', quantity: 5 }
const array1 = [5, 12, 8, 130, 44];
const found = array1.find(element => element > 10);
console.log(found);
// expected output: 12
let arr = ["Bill", "Russel", "John", "Tom", "Eduard", "Alien", "Till"];
Array.prototype.myFind = function (callback) {
for (let i = 0; i < this.length; i++) {
if ( true == callback(this[i], i, this)) {
return {element:this[i],index:i,array:this};
}
}
};
let {element,index,array} = arr.myFind((element) => element[0] === "T");
console.log(`This is ${element} in index of ${index} in array ${array}`);
Run code snippetHide results
/* This method returns first element of the array that satisfies the condition
specified in the callback function.
*/
const x = [1, 2, 3, 4, 5];
const y = x.find(el => el*2 === 2);
console.log("y is: ", y); // y is: 1
/* Now, if you see the output of the above example, the value of y is 1.
This is because the find() method searches for first element in the array
that satisfies the condition specified.
*/