Created
December 25, 2016 18:20
-
-
Save aamnah/8e6e9245b6faa9bc01b261265ddcbc85 to your computer and use it in GitHub Desktop.
Code examples for Array .filter() method
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
let items = [ 1, 2, 3, 4, 5, 6 ] | |
let filtered = items.filter(x => x > 3) | |
console.info('filtered:', filtered) // filtered: [ 4, 5, 6 ] |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
let stocks = [ | |
{ symbol: "APL", price: 693 }, | |
{ symbol: "HUBC", price: 103 }, | |
{ symbol: "POL", price: 413 } | |
] | |
function stocksOver(stocks, minPrice) { | |
return stocks.filter(stock => stock.price >= minPrice) | |
} | |
let expensiveStocks = stocksOver(stocks, 150) | |
console.log(expensiveStocks) // [ { symbol: 'APL', price: 693 }, { symbol: 'POL', price: 413 } ] |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
let people = [ | |
{name: 'Aamnah', pets: ['cat', 'dog']}, | |
{name: 'Ali', pets: ['dog']}, | |
{name: 'Simon', pets: ['horse']}, | |
{name: 'Ben', pets: []} | |
] | |
let filter1 = people.filter(x => x.pets.length) // only get objects where the pets property array has a value | |
console.info('filter1:', filter1) | |
let filter2 = people.filter(x => x.pets) // only get objects where the pets property exists | |
console.info('filter2:', filter2) | |
let filter3 = people.filter(x => x.pets.indexOf('dog') > -1) // only get objects where the pets property contains a dog | |
console.info('filter3:', filter3) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment