Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Code examples for Array .filter() method
let items = [ 1, 2, 3, 4, 5, 6 ]
let filtered = items.filter(x => x > 3)
console.info('filtered:', filtered) // filtered: [ 4, 5, 6 ]
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 } ]
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
You can’t perform that action at this time.