Use filter method in JavaScript Array

The Filter method enables you to filter data from an Array as per a rule you provide. It creates a new Array of all the elements that pass the test condition. Simple and Easy to implement.

A simple example of the JavaScript filter() can be as follows

ES5 Version

var numbers = [12, 33, 5, 22, 44, 1, 45, 22, 666, 323, 12, 22, 4];

var ES5_numberLessThanHundred = numbers.filter(function(number) {
return number < 100;
});

console.log(ES5_numberLessThanHundred)

ES6 Version

var numbers = [12,33,5,22,44,1,45,22,666,323,12,22,4];

var numberLessThanHundred = numbers.filter(number=>number<100);

console.log(numberLessThanHundred)

You can see it in action out here on the REPL. The sample carries both ES5 and ES6 versions of the code. This way there can be numerous filters that can be written in order to filter arrays.

Use cases

  1. Filtering
  2. Searching
  3. Searching through JSON Objects
  4. Conditional Filtering

Check out all the other posts on JavaScript Essentials to get a Grasp of these JavaScript Utilities.


Originally published at The Web Juice.