Array methods in Javascript
Some methods: map(), filter(), sort() and reduce()... Everyone heard about built-in javascript methods which help us to write reliable and clean code, but many people don’t use them because they don’t know them exactly.
Let’s see how to use them! I try to provide simple examples to catch the main idea behind them.
Get Tamás Kovács’s stories in your inbox
Join Medium for free to get updates from this writer.
The map() helps you creating a new array based on the old one. You don’t need to write for cycles. You can be sure the map() function doesn’t mutate the original object, don’t be afraid of side-effects.
let elements = [1, 2, 3, 4];
let increasedElements = elements.map(number => number + 1);
console.log(elements); // [1, 2, 3, 4]
console.log(increasedElements); // [2, 3, 4, 5]
console.log(increasedElements === elements); // falseThe filter() creates a new array with that elements which pass the test by the function in the parameters. The provided function returns only boolean result. No mutation, no side-effects.
let elements = [1, 5, 10, 15];
let filteredElements = elements.filter(number => number >= 10);console.log(elements); // [1, 5, 10, 15]
console.log(filteredElements); // [10, 15]
console.log(filteredElements === elements); // false
The sort() method regularly used to sort the elements of an array. Heads up! The sort() method mutates your object! Using it by default without a compare function is not a good idea. Just check this simple example, when you have to sort an array of numbers.
let numbers = [1, 5, 71, 7, 8];
numbers.sort();console.log(numbers); // [1, 5, 7, 71, 8]
The result is unexpected, because the sort order is according to string Unicode code points. If you want to compare numbers, you have to implement your own compare function.
let numbers = [1, 5, 71, 7, 8];numbers.sort( (a, b) => {
if (a === b ) {
return 0;
} return (a < b ) ? -1 : 1;
});console.log(numbers); // [1, 5, 7, 8, 71]
The reduce() method can be a huge help, when you reduce an array to a single value. You can read the detailed documentation on MDN about this method which provide much more possibilities as my stupid simple example. But it can show the greatness of this method.
let elements = [1, 2, 3];
let initialValue = 0;
let sum = elements.reduce( (total, element) => {
console.log(total, element); // 0, 1 .. 1, 2 .. 3, 3 .. 6
return total + element;
}, initialValue);console.log(sum); // 6
I hope you enjoyed the short explanations of this methods. I am going to write a series of this articles to explore the beautiful complexity / simplicity if Javascript.
Special thanks for every resources what i used to learn about javascript best practices:
Sven Slootweg http://cryto.net/~joepie91/blog/2015/05/04/functional-programming-in-javascript-map-filter-reduce/
Mozilla Developer Network — https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array








