Array `filter()` in JavaScript

Oct 15, 2019

The Array#filter() function takes a callback function, and returns a new array of elements for which callback returns a truthy value.

const numbers = [1, 2, 3, 4, 5, 6];

let callback = v => v % 2 === 0;
const even = numbers.filter(callback);
even; // [2, 4, 6]

callback = v => v % 2 === 1;
const odd = numbers.filter(callback);
odd; // [1, 3, 5]

Remember that filter() returns a new array. It does not modify the existing array.

even === numbers; // false
odd === numbers; // false
even === odd; // false

numbers.length; // 6, `filter()` does not modify `numbers`

filter() behaves like a shallow clone: it only clones the top-level array, not any objects in the array.

const people = [
  { name: 'Jean-Luc Picard', rank: 'Captain' },
  { name: 'Will Riker', rank: 'Commander' },
  { name: 'Geordi La Forge', rank: 'Lieutenant' }
];

const filtered = people.filter(p => p.rank === 'Lieutenant');

// Although `filtered` is a new array, it still points to
// the same objects, so modifying an object in the filtered
// array also affects the original array.
filtered[0] === people[2]; // true
filtered[0].rank = 'Lieutenant Commander';
people[2].rank; // 'Lieutenant Commander'

Did you find this tutorial useful? Say thanks by starring our repo on GitHub!

More Fundamentals Tutorials

×
Mastering JS
Hi, I'm a JavaScript programming bot. Ask me something about JavaScript!