Searching element in array is very common functionally that we often need in web application development, there can be different type of search requirement, in JavaScript we have built-in functionality like find filter etc, let’s see how we can write search function.
const array1 = [15, 13, 8, 140, 84, 51, 3];
Now searching an element from array list is-done differently in different programming language, In this tutorial, we will learn how to search element in javascript array.
In following example, we will find the first matching element from JavaScript array.
const array1 = [15, 13, 8, 140, 84, 51, 3]; const found = array1.find(element => element > 10); console.log(found);
Above code will give you result “15”, the first number which is greater than 10, all other number will be ignored.
Now think of situation where we want all the items that satisfy the conditions.
Here we use array filter to search all elements from an array.
let array2 =[15, 13, 8, 140, 84, 51, 3]; function checkConditions(v1) { return v1 >= 10; } var filtered = array2.filter(checkConditions); console.log(filtered);
The above code will return an array of all the number like [ 15, 13, 140, 84, 51 ]
, which are greater than 10.
Let's look at another example of string array, we want to find all elements which has length more than 6 character.
const words = ['red', 'green', 'park', 'big', 'elephant', 'roaming']; const result = words.filter(word => word.length > 6); console.log(result);
Remember, filter method will always return an array.
In above code we are searching all array elements based on their length, we see result [ 'elephant', 'roaming' ]
, all string values which has more than 6 character length.
Searching item json array is like searching in list it, for example we have a array containing list of students with their details like name, email, mobile, location etc, now we want to search students based on some attribute value, let’s say search students where location is Kolkata.
const students = [ {id: 1, name: 'Anusua', location: 'Kolkata' }, {id: 2, name: 'Debopriya', location: 'Mumbai' }, {id: 3, name: 'Deepak', location: 'Hyderabad' }, {id: 4, name: 'Gargi', location: 'Kolkata' } ] var s1 = students.filter(function(item) { return item.location === 'Kolkata'; }); console.log(s1);
Above code will return an array as result with all student details where matching specified location. result will look like ..
[
{ id: 1, name: 'Anusua', location: 'Kolkata' },
{ id: 4, name: 'Gargi', location: 'Kolkata' }
]
You may be interested in following posts: