EN
JavaScript - how to filter array
0 points
In this article, we would like to show you how to filter an array in JavaScript.
In this section, we present how to filter a simple array of numbers to get values greater than 3
.
xxxxxxxxxx
1
const numbers = [1, 2, 3, 4, 5];
2
3
const result = numbers.filter((number) => number > 3);
4
5
console.log(result); // [ 4, 5 ]
In this example, we have food
array with some records. We filter the array using filter()
method to get only food with fruit
type.
xxxxxxxxxx
1
const food = [
2
{name: 'Apple', type: 'fruit'},
3
{name: 'Broccoli', type: 'vegetable'},
4
{name: 'Banana', type: 'fruit'},
5
{name: 'Fries', type: 'fast-food'},
6
{name: 'Cherry', type: 'fruit'}
7
];
8
9
const fruits = food.filter((item) => item.type === 'fruit');
10
11
console.log(JSON.stringify(fruits, null, 4));