search in an array javascript code example

Example 1: find element in array javascript

const simpleArray = [3, 5, 7, 15];
const objectArray = [{ name: 'John' }, { name: 'Emma' }]

console.log( simpleArray.find(e => e === 7) )
// expected output 7

console.log( simpleArray.find(e => e === 10) )
// expected output undefined

console.log( objectArray.find(e => e.name === 'John') )
// expected output { name: 'John' }

Example 2: 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)

Example 3: how to find id in array javascript

//The find() method returns the value of the first element in the provided array that satisfies the provided testing function.
const array1 = [5, 12, 8, 130, 44];

const found = array1.find(element => element > 10);

console.log(found);
// expected output: 12

Example 4: find method javascript

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 }