How to use Array.find() method In Javascript
In this approach we are using Array.find() to iterate over the array and objects. The Array. find() method in JavaScript is a handy tool for searching through an array and retrieving the first element that satisfies a specified condition then we use some() to search nested arrays for the given character. It returns a boolean result.
Syntax:
arr.find(callback(element,index,array),thisArg);
Example: In this example, The myFunction takes an array of objects and a character as parameters. It uses Array.find() and Array.some() to search for the character within nested arrays. Returns true if found, otherwise false
Javascript
function myFunction(arrayOfObjects, char) { return ( arrayOfObjects.find((obj) => obj.charLists.some((charList) => charList.includes(char)) ) !== undefined ); } const arrayOfObjects = [ { charLists: [ "HTML" , "CSS" , "JavaScript" ] }, { charLists: [ "React" , "Redux" , "Routes" ] }, { charLists: [ "10" , "20" , "30" ] }, ]; const result1 = myFunction(arrayOfObjects, "React" ); console.log(result1); const result2 = myFunction(arrayOfObjects, "PHP" ); console.log(result2); const result3 = myFunction(arrayOfObjects, "20" ); console.log(result3); |
true false true
How to Search Character in List of Array Object Inside an Array Object in JavaScript ?
Searching for a character in a list of array objects inside an array object involves inspecting each array object, and then examining each array within for the presence of the specified character. The goal is to determine if the character exists within any of the nested arrays. There are several ways to search for characters in a list of array objects inside an array of objects which are as follows:
Table of Content
- Using forEach() loop
- Using Array.some() and Array.includes()
- Using Array.find() method
- Using reduce() method