Filter an Array with JavaScript

Last Updated On Wednesday 19th Jan 2022

JavaScript Filter

How to filter arrays in JavaScript using the Array Filter method ?

What does filter function do?

  • The filter() method creates a new array with array elements that passes a test.
  • The filter() method takes a callback function which has 3 arguments.

Syntax JavaScript Array Filter

	array.filter(function(value, index, arr), thisValue)
	
	let numbers = [-11,-22,-33, -1, -5, 0, 2, 42, 32, 19, 85];

let getPostiveNumbers = numbers.filter(number => number >= 0);

console.log(getPostiveNumbers);

//Output = [0, 2, 42, 32, 19, 85 ]
	
	let users = [
  {
    "name": "Keith",
    "used": "Samsung Galaxy",
    "id": "1"
  },
  {
    "name": "Sum Rae",
    "used": "OnePlus Nord",
    "id": "2"
  },
  {
    "name": "Alan",
    "used": "OnePlus Nord",
    "id": "3"
  },
  {
    "name": "Jonathan",
    "used": "iPhone 12",
    "id": "4"
  },
  {
    "name": "Jarvo",
    "used": "iPhone 12",
    "id": "5"
  }
];
	
	let iPhoneUsers = users.filter(function(user) {
    return used.used == "iPhone 12"; });

console.log(iPhoneUsers);
	
	[
  { name: 'Jonathan', used: 'iPhone 12', id: '4' },
  { name: 'Jarvo', used: 'iPhone 12', id: '5' }
]
	

JavaScript Filter Array

If you more comfortable with arrow functions you can use them to make your code more readable.

	let iPhoneUsers = users.filter(user => user.used == "OnePlus Nord");

console.log(iPhoneUsers);
	
	[
  { name: 'Sum Rae', used: 'OnePlus Nord', id: '2' },
  { name: 'Alan', used: 'OnePlus Nord', id: '3' }
]
	

References