JavaScript Array Filter With some examples

In this tutorial we will learn about Filter An Array In JavaScript with some examples. Array is an important part of any programming language which is mostly used to manipulate the data. An array contains iterable data which can be iterate using loop.

javascript array filter

How To Search Data in An Array or Objects of Array In JavaScript Using Filter() Method.

To search the strings inside the filter, we will use includes() function. Filter function returns all those elements which are matching with the input value.

Example:

Like I have an array which have following elements:

var names = [“Ramesh”, “Rama”, “ramanuj”, “sita raman”, “krishna”];
var filteredArray = names.filter(val =>(val.toLowerCase()).includes(“ram”));

Result:

=> Ramesh, Rama, ramanuj

The filter() method will search the characters which we provided, if they matches inside any string inside the array, it will return those.

The includes() method returns true if any part of string find otherwise return false.

Filtering Objective Array in JavaScript

This is also same as filtering the above array. To access the key use the key name from Object of the array.

var names = [{name: “Ramesh”, age:24}, {name: “Rama”, age: 27}, {name: “ramanuj”, age: 21}, {name: “sita raman”, age: 35}, {name: “krishna”, age: 45}];
var filteredArray = names.filter(val =>(val.name.toLowerCase()).includes(“ram”));

Result: Because ram is matching in Ramesh, Rama and ramanuj.

=> [{name: “Ramesh”, age:24}, {name: “Rama”, age: 27}, {name: “ramanuj”, age: 21}];

We can write any condition inside this filter() function and then execute with its elements like greater/lesser/equal values as below.

How to Filter Greater/Lesser Values From An Array in JavaScript?

Getting those persons whose age is greater than 30. For this we will write the greater condition inside the filter() function as below:

var names = [{name: “Ramesh”, age:24}, {name: “Rama”, age: 27}, {name: “ramanuj”, age: 21}, {name: “sita raman”, age: 35}, {name: “krishna”, age: 45}];
var filteredArray = names.filter(val => val.age > 30);

Result:

It will return those Array Objects which age is greater than 30.

[{name: “sita raman”, age: 35}, {name: “krishna”, age: 45}];

Thank you for visiting the page on FlutterTPoint. Suggested post is includes(). You can comment in the comment section below. Hope you learn how to use filter() function in JavaScript to search inside an array.

Don’t miss new tips!

We don’t spam! Read our [link]privacy policy[/link] for more info.

Leave a Comment

Translate »
Scroll to Top