codeburst

Bursts of code to power through your day. Web Development articles, tutorials, and news.

Follow publication

Learn & Understand JavaScript’s Filter Function

Brandon Morelli
codeburst
Published in
4 min readNov 13, 2017

This is article #2 in a four part series this week.

Filter Definition & Syntax

let newArr = oldArr.filter(callback);

Filter vs. For Loop Example

let arr = [1, 2, 3, 4, 5, 6];
let even = [];
for(var i = 0; i < arr.length; i++) {
if (arr[i] % 2 === 0) even.push(arr[i]);
}
// even = [2,4,6]
let arr = [1,2,3,4,5,6];
let even = arr.filter(val => {
return val % 2 === 0;
});
// even = [2,4,6]

Filter Example #2

let data = [
{
country: 'China',
population: 1409517397,
},
{
country: 'India',
population: 1339180127,
},
{
country: 'USA',
population: 324459463,
},
{
country: 'Indonesia',
population: 263991379,
}
]
let cities = data.filter(val => {
return val.population > 500000000;
});
// cities = [{country: "China", population: 1409517397},
{country: "India", population: 1339180127}]

Filter & ES6

let cities = data.filter(val => {
return val.population > 500000000;
});
let cities = data.filter(val => val.population > 500000000);

Closing Notes:

If this post was helpful, please click the clap 👏button below a fewtimes to show your support! ⬇⬇

Published in codeburst

Bursts of code to power through your day. Web Development articles, tutorials, and news.

Written by Brandon Morelli

Creator of @codeburstio — Frequently posting web development tutorials & articles. Follow me on Twitter too: @BrandonMorelli

Responses (13)

Write a response

Don’t you mean you only return countries? Probably wrong but I didn’t see a single city in this article.

--

Nice read. Can you please point me in the direction of the new ES6 explanation about the arrow function? I get it, but an understanding of the differences of the before and after would be helpful.
Thanks.

--