Javascript built in array methods ES5 and ES6

Inspired by a Sitepoint article:

https://www.sitepoint.com/filtering-and-chaining-in-functional-javascript/

They highlighted built in javascript array methods. I decided to explore two ES5 and ES6 built in array methods; filter and map.

Javascript Array Filter ES5 and ES6

The filter method lets you easily filter an array using a callback style approach. Your callback handles the condition, the filter loops through your array and lets you apply the condition to each value in the array.

1
array.filter(function)

// ES5

1
2
3
4
5
6
7
var list = ['oranges','apples','pears'];
var filteredList = list.filter(
function(value) {
// condition
return value.length <= 5;
}
)

// Result: filteredList = [“pears”]

// ES6

1
2
3
4
let list = ['oranges','apples','pears'];
let filteredList = list.filter(
value => value.length <= 5
)

// Result: filteredList = [“pears”]

Javascript Array Map ES5 and ES6

Use map to loop through elements of an array, on each loop you can create a new element that is appended to a new array. The result of map is a new array, based on the return value in the function in the map declaration.

1
array.map(function)

// ES 5

1
2
3
4
var list = ['oranges','apples','pears'];
var filteredList = list.map(function(value) {
return value.length;
})

// result: filteredList = [7, 6, 5]

// ES 6

1
2
3
4
let list = ['oranges','apples','pears'];
let filteredList = list.map(
value => value.length
)

// result: filteredList = [7, 6, 5]

Chaining javascript array methods; filter and map

As mentioned in the article, a great feature to these array methods is the ability to chain them:

// ES 5

1
2
3
4
5
6
7
8
9
var list = ['oranges','apples','pears'];
var filteredList = list.filter(
function(value) {
// condition
return value.length <= 5;
}
).map(function(value) {
return value.length;
})

// result: filteredList = [5]

// ES 6

1
2
3
4
5
6
let list = ['oranges','apples','pears'];
let filteredList = list.filter(
value => value.length <= 5
).map(
value => value.length
)

// result: filteredList = [5]

Conclusion

There are many more powerful lightweight built in javascript methods that are worth exploring. Taking the time to learn them can help save time and effort.