New(ish) JavaScript Array Methods


There’s a whole load of array methods in JavaScript that are forgot about either because they are new or they have questionable Internet Explorer support. As a rule most of these are available in IE post version 9, so unless that bothers you it’s safe to use them. There’s polyfills available if you need them.

forEach()

The forEach() method executes a callback function once for every element in an array.

var arr = ['Locke', 'Reyes', 'Ford', 'Jarrah', 'Shephard', 'Kwon'];

arr.forEach(function(el, index, arr){
    console.log(el);
    console.log(index);
});

//logs Locke, Reyes, Ford, Jarrah, Shephard, Kwon
//logs 0, 1, 2, 3, 4, 5

every()

The every() method tests whether all elements in the array pass the test implemented by the provided function. Will return true if all array elements pass the condition.

var arr = [4, 8, 15, 16, 23, 42];

arr = arr.every(function(el){
    return el > 10;
});

console.log(arr); //returns false

some()

The some() method tests whether some element(s) in the array passes the test implemented by the provided function. Will return true if at least one element passes the condition.

var arr = [4, 8, 15, 16, 23, 42];

arr = arr.some(function(el){
    return el > 1;
});

console.log(arr); //returns true

filter()

The filter() method creates a new array with all elements that pass the condition i the callback function.

var arr = [4, 8, 15, 16, 23, 42];

console.log(arr); //logs [4, 8, 15, 16, 23, 42]

arr = arr.filter(function(el){
    return el > 10;
});

console.log(arr); //logs [15, 16, 23, 42]

map()

The map() method creates a new array with the results of calling a callback function on the array elements.

var arr = [4, 8, 15, 16, 23, 42];

console.log(arr); //logs [4, 8, 15, 16, 23, 42]

arr = arr.map(function(el, index){
    return el + 1;
});

console.log(arr); //logs [5, 9, 16, 17, 24, 43]

isArray()

The Array.isArray() method returns true if an object is an array.

var arr = ['Locke', 'Reyes', 'Ford', 'Jarrah', 'Shephard', 'Kwon'];

console.log(Array.isArray(arr)); //logs true

Other Resources