Author -  Sai gowtham

How to use array.filter() method in JavaScript

In es6, we got more useful methods in javascript, where one of them is filter() method that help us to filter the particular set of elements from the array.

Consider we have an array of numbers from 1 to 10, but we need only odd numbers from the array.

const numbers  = [1,2,3,4,5,6,7,8,9,10];

We can use filter method to find the odd numbers.

const oddNumbers = numbers.filter((e, i) => e % 2 === 1);

console.log(oddNumbers);

//  [1,3,5,7,9]

filter() method

The filter() method creates a new array with the elements that passes the test condition (callback function).

syntax:

array.filter(function (element, index, array){
    return condition;
})

It runs the callback function on the each element present in the array and keeps the elements whose return value is true or false to exclude it.

We can also use filter() method to filter the array of objects.


const users = [
    {id:1,name:"mas",present:true},
    {id:2,name:"gowtham",present:false},
    {id:3,name:"king",present:true},
    {id:4,name:"major",present:false},
    {id:5,name:"lol",present:false},
    {id:6,name:"seth",present:true},
]

const presentUsers = users.filter((user) => user.present);

console.log(presentUsers);

Output:

[
    { id: 1, name: "mas", present: true },
    { id: 3, name: "king", present: true },
    { id: 6, name: "seth", present: true }
]

Css Tutorials & Demos

How rotate an image continuously in CSS

In this demo, we are going to learn about how to rotate an image continuously using the css animations.

How to create a Instagram login Page

In this demo, i will show you how to create a instagram login page using html and css.

How to create a pulse animation in CSS

In this demo, i will show you how to create a pulse animation using css.

Creating a snowfall animation using css and JavaScript

In this demo, i will show you how to create a snow fall animation using css and JavaScript.

Top Udemy Courses

JavaScript - The Complete Guide 2023 (Beginner + Advanced)
JavaScript - The Complete Guide 2023 (Beginner + Advanced)
116,648 students enrolled
52 hours of video content
$14.99 FROM UDEMY
React - The Complete Guide (incl Hooks, React Router, Redux)
React - The Complete Guide (incl Hooks, React Router, Redux)
631,582 students enrolled
49 hours of video content
$24.99 FROM UDEMY
Vue - The Complete Guide (w/ Router, Vuex, Composition API)
Vue - The Complete Guide (w/ Router, Vuex, Composition API)
203,937 students enrolled
31.5 hours of video content
$14.99 FROM UDEMY