Common array operations in JavaScript JavaScript 12.08.2014

Creating a Array object

var arr = new Array(1, 2, ,3)
var arr = [1, 2, 3]

Return an array as a string

arr.toString()

Join all array elements into a string

arr.join('|')

Remove the last element from an array

arr.pop()

Add a new element to an array (at the end)

arr.push(4)

Add more than one item at a time

arr.push(5, 6)

Add the contents of one array to another

var arr1 = [1, 2, 3];
var arr2 = [4, 5, 6];
arr1.push.apply(arr1, arr2);

Create a new array from the contents of two arrays

var arr1 = [1, 2, 3];
var arr2 = [4, 5, 6];
var arr3 = arr1.concat(arr2);

Remove the first element of an array, and "shifts" all other elements one place down

arr.shift()

Add a new element to an array (at the beginning), and "unshifts" older elements

arr.unshift(0)

Add items to the beginning of an array

arr.unshift(-1, 0)

Delete element

delete arr[0]

Add new items to an array

arr.splice(2, 0, 10, 11)

The first parameter (2) defines the position where new elements should be added (spliced in). The second parameter (0) defines how many elements should be removed. The rest of the parameters (10, 11) define the new elements to be added.

map() method creates a new array with the results of calling a provided function on every element in an array

arr.map(function(i){return i + 2})

filter() method creates a new array with all elements that pass the test implemented by the provided function

arr.filter(function(i){return i > 2})

sort() method cannot be used on a number array, because it sorts alphabetically (25 is bigger than 100).

arr.sort()

every() method tests whether all elements in the array pass the test implemented by the provided function

arr.every(function(i){return i > 2})

some() method tests whether some element in the array passes the test implemented by the provided function

arr.some(function(i){return i > 2})

reduce() method applies a function simultaneously against two values of the array (from left-to-right) as to reduce it to a single value

arr.reduce(function(x,y){return x+y})

indexOf() method returns the first index at which a given element can be found in the array, or -1 if it is not present.

arr.indexOf(2)