Notes

Array.filter()

Edit on GitHub

JavaScript
2 minutes

.filter()

gives a new array after filtering an array based on the truth/false of a condition

Examples

1. get expensive stocks

Here’s an array of stocks.

1let stocks = [
2  { symbol: "APL", price: 693 },
3  { symbol: "HUBC", price: 103 },
4  { symbol: "POL", price: 413 }
5]

We’ll get the expensive stocks (let’s say the ones which cost more than 150) out of it with filter()

1function stocksOver(stocks, minPrice) {
2 return stocks.filter(stock => stock.price >= minPrice)
3}
4
5let expensiveStocks = stocksOver(stocks, 150)
6
7console.log(expensiveStocks) // [ { symbol: 'APL', price: 693 }, { symbol: 'POL', price: 413 } ]

2. get a subset of an array

Here’s a simpler example:

1let items = [ 1, 2, 3, 4, 5, 6 ]
2let filtered = items.filter(x => x > 3)
3
4console.info('filtered:', filtered) // filtered: [ 4, 5, 6 ]

3. filter based on object properties

 1let people = [ 
 2	{name: 'Aamnah', pets: ['cat', 'dog']}, 
 3	{name: 'Ali', pets: ['dog']},
 4	{name: 'Simon', pets: ['horse']},
 5	{name: 'Ben', pets: []},
 6	{name: 'Max'}
 7]
 8
 9let filter1 = people.filter(x => x.pets) // only get objects where the pets property exists
10console.info('filter1:', filter1)
11
12let filter2 = people.filter(x => x.pets.length) // only get objects where the pets property array has a value
13console.info('filter2:', filter2)
14
15let filter3 = people.filter(x => x.pets.indexOf('dog') > -1) // only get objects where the pets property contains a dog
16console.info('filter3:', filter3)

x.pets.length and x.pets.indexOf('dog') will both give an error TypeError: Cannot read property 'indexOf' of undefined if the pets property does not exist. Use an if statement here to get your desired results

1let filter1 = people.filter(x => x.pets) // only get objects where the pets property exists
2console.info('filter1:', filter1)
3
4let filter2 = people.filter(x => {
5	if (x.pets) {
6		x.pets.length && console.info('pets:', x) 
7		x.pets.indexOf('dog') > -1 && console.info('dog owners:', x)
8	}
9})

Related