vanilla javascript search array of objects for property code example

Example 1: javascript find object in array by property value

const fruits = ['apple', 'banana', 'grapes', 'mango', 'orange'];

const filterItems = (needle, heystack) => {
  let query = needle.toLowerCase();
  return heystack.filter(item => item.toLowerCase().indexOf(query) >= 0);
}

console.log(filterItems('ap', fruits)); // ['apple', 'grapes']
console.log(filterItems('ang', fruits)); // ['mango', 'orange']

Example 2: find object in array by property javascript

// Find an object with a given property in an array
const desiredObject = myArray.find(element => element.prop === desiredValue);