Useful Array Javascript methods

There are many times when a developer need to do some modification of an array. The easiest way to achieve that is to use for loop and this is exactly how a web developer beginner will do it. This short article shows how to do it the right way — functional way using native array methods and leaving more readable code.

Beginner’s code — for loop

A for loop is not bad, there are many situations where you can use it. The problem is that the code is not readable and redundant. Using only for loop when programming in Javascript can be also cumbersome. You can avoid that by using Array methods already provided by the language. For example this code:

var arr1 = [“A”, ”B”, ”C”, ”D”];
var arr2;
function build(arr){
for(var i = 0 ;i < arr.length; i++) {
arr2.push({name: arr[i]});
}
}
build(arr1);

can be easily changed to this:

arr2 = arr1.map(function(a){return {name: a}});

Most popular methods

Javascript provides many built-in methods used to operate on an array. The ones I often use are shown below with a very simple description of what they are intended to do:

  • map() — will apply a given function to every element of an array. To be more specific — it will return a new array that contains every element of input array transformed with a given function. A good example is when we want to add 1 to every item in the array — this is where to use map().
  • filter() — will return elements from input array that pass testing them with given function. This can be used to select a couple values from input array based on a given condition. As an example — selecting only even number can be done with filter().
  • find() is similar to filter() but returns first element valid. It is useful to search for particular value if you are sure that array element is unique. You can also do the opposite — implement a function that searches for an invalid element to validate if the array is correct.
  • some() — very similar to find() but instead of giving back the first element that fulfils given condition it returns a boolean value if the element is found in given array.
  • reduce() — will apply a given function to a whole array. Comparing to map() which takes elements, apply a function to them individually and returns an array, this will function to the array as a whole — the result of the first element will be used to produce a result of the second element and so on. To give a vivid example — the sum of elements can be done by using reduce().

Examples of usage

Javascript array methods can be used individually or mixed in a single function to give you the result you wanted. You can combine multiple methods and chain them as presented below. Just check the example codes and don’t hesitate to play with it.

This will return only unique named elements from array:

var array = [ {id: 1, name: ‘tommy’}, 
{id: 2, name: ‘tommy’},
{id: 3, name: ‘alex’},
{id: 4, name: ‘greg’},
{id: 5, name: ‘tommy’}];

array.filter(function(a) {
return !array.some(function(b) {
return (a.name === b.name) && (a !== b);
});
});

This one will select only true elements from the list:


var hash = {A: true, B: true, C: false, D: false, E: true, F: true};
function selectObjects(hash) {
var keys = Object.keys(hash)
.filter(function(key) {return hash[key] === true;})
.reduce(function(arr, key) {return arr.concat(key);},[]);
return keys;
}

Functional programming

Using Javascript Array methods is not only about making your code a lot of quicker to read and less intricate. It allows you to add a bit of functional programming style to your application. A simple example of imperative code compared to functional one is here:

Imperative:

const numbers = [1, 2, 3, 4, 5]
let result = 0
for(var i = 0 ;i < numbers.length; i++) {
if (n % 2) {
result += n * n
}
}
console.log(result)

Functional:

const numbers = [1, 2, 3, 4, 5]
const result = numbers
.filter(isOdd)
.map(square)
.reduce(sumReducer, 0)
console.log(result)
function isOdd (n) { return n % 2 }
function square (n) { return n * n }
function sumReducer (r, n) { return r + n }

The results given by those functions will be the same. Reading the javascript code written in a functional way is less quizzical than imperative one, it also allows you to reuse functions in other places.

I really recommend spending some time at the Javascript reference to become familiar with those native Array methods. It will just make your work much easier.