The JavaScript Array find method is a way to find and return the first occurrence of an element in an array , Array.find only return a single matched element , if nothing is find then it return undefined
var array = ['cat', 'dog' , 'car'];
var found = array.find(function (element) {
return element == 'dog';
});
document.write(found); // return dog
var array = [10, 20, 30, 40];
var found = array.find(function (element) {
return element > 10;
});
document.write(found); // return 20
Array find with startsWith javascript function
const vehicles = [
"car",
"bus",
"truck",
"SUV"
];
const result = vehicles.find(tree => tree.startsWith("c"));
document.write(result) ; // car
Array Find using JavaScript object
const vehicles = [
{ name: "car", count: 4 },
{ name: "bus", count: 5 },
{ name: "SUV", count: 2 }
];
const result = vehicles.find(vehicle => vehicle.name == 'SUV');
console.log(result); // {name: "SUV", count: 2}
Array Find on a JavaScript object with index i
const vehicles = [
{ name: "car", count: 4 },
{ name: "bus", count: 5 },
{ name: "SUV", count: 2 }
];
const result = vehicles.find((vehicle, i) => {
if (vehicle.count > 1 && i !== 0) return true;
});
console.log(result); // {name: "bus", count: 5}
Top comments (0)