search in array code example
Example 1: js get array item by property
const jsObjects = [
{id: 1, displayName: "First"},
{id: 2, displayName: "Second"},
{id: 3, displayName: "Third"},
{id: 4, displayName: "Fourth"}
]
var result = jsObjects.find(obj => {
return obj.id === 1
})
console.log(result)
Example 2: array_search in php
<?php
$array = array(0 => 'blue', 1 => 'red', 2 => 'green', 3 => 'red');
$key = array_search('green', $array);
$key = array_search('red', $array);
?>
Example 3: find element in array javascript
const simpleArray = [3, 5, 7, 15];
const objectArray = [{ name: 'John' }, { name: 'Emma' }]
console.log( simpleArray.find(e => e === 7) )
console.log( simpleArray.find(e => e === 10) )
console.log( objectArray.find(e => e.name === 'John') )
Example 4: js get index of item in array
array.indexOf("item");
Example 5: javascript array.find
const array1 = [5, 12, 8, 130, 44];
const found = array1.find(element => element > 10);
console.log(found);
Example 6: function search in javascript array
function findInArray(ar, val) {
for (var i = 0,len = ar.length; i < len; i++) {
if ( ar[i] === val ) {
return i;
}
}
return -1;
}
var ar = ['Rudi', 'Morie', 'Halo', 'Miki', 'Mittens', 'Pumpkin'];
alert( findInArray(ar, 'Rudi') );
alert( findInArray(ar, 'Coco') );