Languages
[Edit]
EN

JavaScript - how to filter array

0 points
Created by:
Kevin
797

In this article, we would like to show you how to filter an array in JavaScript.

1. Filter array

In this section, we present how to filter a simple array of numbers to get values greater than 3.

// ONLINE-RUNNER:browser;

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

const result = numbers.filter((number) => number > 3);

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

2. Filter array of objects

In this example, we have food array with some records. We filter the array using filter() method to get only food with fruit type.

// ONLINE-RUNNER:browser;

const food = [
	{name: 'Apple', type: 'fruit'},
	{name: 'Broccoli', type: 'vegetable'},
 	{name: 'Banana', type: 'fruit'},
 	{name: 'Fries', type: 'fast-food'},
 	{name: 'Cherry', type: 'fruit'}
];

const fruits = food.filter((item) => item.type === 'fruit');

console.log(JSON.stringify(fruits, null, 4));

References

Alternative titles

  1. JavaScript - how to filter array of objects
  2. JavaScript - how to filter array of numbers
  3. JavaScript - get array of elements fulfilling condition
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join