This post assumes prior knowledge of:
- Array Iterations
- Callback Functions
const catalog = [
{ name: 'Hammer', desc: 'A π¨', price: 1.5, id: 1 },
{ name: 'Chainsaw', desc: 'Cut up π§ββοΈs.', price: 11.5, id: 2 },
{
name: 'Frying Pan',
desc: 'For π¨π½βπ³ing π₯.',
price: 10.5,
id: 3
},
{ name: 'Spatula', desc: 'Use it for grilling.', price: 7.5, id: 4 },
{
name: 'Airplane',
desc: 'For flying around!',
price: 100000000.5,
id: 5
},
{ name: 'Car', desc: 'For driving.', price: 10000.5, id: 6 }
]
// TODO: Create a new Array that contains all of the items with a 'price' less than $100.
const under100 = catalog.fiter(function(item) {
return item.price <= 100;
})
The filter
method is part of Array.prototype.
This means that we can call on it on anything that is a bona fide Array ( catalog
ππ½). It takes in a callback function and return
s a new Array (under100
ππ½). filter
filters an Array by iterating over each element and passing it into its callback function. If the callback function return
s true
, then that element is 'added' to the return
ed Array.
In our example above, item
represents one of the Objects in the Array catalog
. If item
's price
references a value less than or equal to 100
, item
is included in under100
. As you can see, this is why our callback function must return
either true
or false
- this is how we are able to perform 'filtering.'
When filter
ing, the original Array (catalog
) is not mutated (changed) in any way. Instead a separate, new Array is created. Avoiding mutations is usually desirable and is a fundamental of the functional programming paradigm.
β»οΈ Refactoring Our Code Using ES6 Arrow Syntax β‘οΈ
const under100 = catalog.fiter(item => item.price <= 100)
Top comments (0)