Apps Artificial Intelligence CSS DevOps Go JavaScript Laravel Linux MongoDB MySQL PHP Python Rust Svelte Vue

Filter JavaScript Arrays Quickly and Clearly

1 min read .
Filter JavaScript Arrays Quickly and Clearly

Array.prototype.filter() creates a new array containing only the elements that satisfy a predicate. It does not modify the original array.

Filter by a Condition

const values = [1, 2, 3, 4, 5, 6];
const even = values.filter((value) => value % 2 === 0);

console.log(even); // [2, 4, 6]

Filter Objects by a Property

const users = [
  { name: 'Alice', age: 25 },
  { name: 'Bob', age: 30 },
  { name: 'Charlie', age: 25 },
];

const age25 = users.filter((user) => user.age === 25);

Remove Duplicates

For primitive values, a Set is usually clearer than using filter() with indexOf:

const values = [1, 2, 3, 2, 4, 5, 3];
const unique = [...new Set(values)];

console.log(unique); // [1, 2, 3, 4, 5]

For objects, define what makes two records equivalent and track that key explicitly.

Filter and Transform

Array methods compose naturally:

const values = [1, 2, 3, 4, 5];
const result = values
  .filter((value) => value % 2 === 0)
  .map((value) => value * 2);

console.log(result); // [4, 8]

Dynamic Predicates

You can pass a reusable predicate into a helper:

const filterArray = (array, predicate) => array.filter(predicate);

const result = filterArray(
  [1, 2, 3, 4, 5],
  (value) => value >= 3,
);

Conclusion

Use filter() when you want a subset of an array without mutating the source. Keep predicates focused, compose with map or other methods when useful, and prefer purpose-built tools such as Set when they express the operation more directly.

Related Posts

chevron-up