javascript find object by property in array
// To find a specific object in an array of objects
myObj = myArrayOfObjects.find(obj => obj.prop === 'something');
javascript find object by property in array
// To find a specific object in an array of objects
myObj = myArrayOfObjects.find(obj => obj.prop === 'something');
javascript find
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 }
js find value in array
const array1 = [5, 12, 8, 130, 44];
const found = array1.find(element => element > 10);
console.log(found);
// expected output: 12
function search in javascript array
// function to search array using for loop
function findInArray(ar, val) {
for (var i = 0,len = ar.length; i < len; i++) {
if ( ar[i] === val ) { // strict equality test
return i;
}
}
return -1;
}
// example array
var ar = ['Rudi', 'Morie', 'Halo', 'Miki', 'Mittens', 'Pumpkin'];
// test the function
alert( findInArray(ar, 'Rudi') ); // 0 (found at first element)
alert( findInArray(ar, 'Coco') ); // -1 (not found)
array search
/*
Arrays Methods [Search]
- indexOf(Search Element, From Index [Opt])
- lastIndexOf(Search Element, From Index [Opt])
- includes(valueToFind, fromIndex [Opt]) [ES7]
*/
let myFriends = ["Ahmed", "Mohamed", "Sayed", "Alaa", "Ahmed"];
console.log(myFriends);
console.log(myFriends.indexOf("Ahmed"));
console.log(myFriends.indexOf("Ahmed", 2));
console.log(myFriends.lastIndexOf("Ahmed"));
console.log(myFriends.lastIndexOf("Ahmed", -2));
console.log(myFriends.includes("Ahmed"));
console.log(myFriends.includes("Ahmed", 2));
if (myFriends.lastIndexOf("Osama") === -1) {
console.log("Not Found");
}
console.log(myFriends.indexOf("Osama"));
console.log(myFriends.lastIndexOf("Osama"));
js to find value in array
console.log( simpleArray.find(e => e === 7) )
Copyright © 2021 Codeinu
Forgot your account's password or having trouble logging into your Account? Don't worry, we'll help you to get back your account. Enter your email address and we'll send you a recovery link to reset your password. If you are experiencing problems resetting your password contact us