Skip to content
Advertisements

Array filter()

filter () returns data that satisfies the given conditions. The item argument is a reference to the current element in the array as filter() checks it against the condition. This is useful for accessing properties, in the case of objects.
If the current item passes the condition, it gets sent to the new array.

Note: filter() does not execute the function for array elements without values.
Note: filter() does not change the original array.

Syntax:

array.filter(function(Value, index, arr), thisValue)
//value = current

value(Required): The value of the element
index(Optional): The array index of the element
arr(Optional): The array object the element belongs to.


Examples

Example-1

        let ages = [22, 16, 22, 54, 12];
        function ageControl(age) {
            return age >= 18;
        }
        console.log(ages.filter(ageControl))

output:

[22, 22, 54]


Example-2

        let names = [
            { name: "john", surname: "lewis" },
            { name: "rick", surname: "martin" },
            { name: "alexandra", surname: "lewis" }
        ]
        var surnameControl = names.filter(function (x) {
            return x.surname == "lewis"
        })
        console.log(surnameControl)

output:

{name: “john”, surname: “lewis”}
{name: “alexandra”, surname: “lewis”}

Advertisements

2 Comments »

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: