search an array for a value 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: javascript array.find

const array1 = [5, 12, 8, 130, 44];

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

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

Example 3: js array find

var ages = [3, 10, 18, 20];

function checkAdult(age) {
  return age >= 18;
}
/* find() runs the input function agenst all array components
   till the function returns a value
*/
ages.find(checkAdult);

Example 4: search input at array javascript

var people = [
  {
    name: "John Smith",
    url: "http://example.com/johnsmith"
  },
  {
    name: "John Johnson",
    url: "http://example.com/johnjohnson"
  },
  {
    name: "Bob Thompson",
    url: "http://example.com/bobthompson"
  },
  {
    name: "Smith Sanchez",
    url: "http://example.com/smithsanchez"
  },
  {
    name: "Bob Sanchez",
    url: "http://example.com/bobsanchez"
  }
];
$("#search-input").on("keyup", function(){
  var searchFor = $("#search-input").val().toLowerCase();
  var results = [];
  for(var i=0;i<people.length;i++){
    if(people[i].name.toLowerCase().indexOf(searchFor) > -1)
      results.push("<a href='"+people[i].url+"' target='_blank'>"+people[i].name+"</a>")
  }
  if(results.length == 0)
    $("#search-results").html("No Results Found");
  else
    $("#search-results").html(results.join("<br>"));
});