JavaScript arrays over time got more and more features, sometimes it’s tricky to know when to use some construct vs another. This post aims to explain what you should use, as of 2017.

Initialize array

const a = []
const a = [1,2,3]
const a = Array.of(1,2,3)
const a = Array(6).fill(1); //init an array of 6 items of value 1

Don’t use the old syntax (just use it for typed arrays)

const a = new Array() //never use
const a = new Array(1,2,3) //never use

Get length of the array

const l = a.length

Iterating the array

Every

a.every(f)

Iterates a until f() returns false

Some

a.some(f)

Iterates a until f() returns true

Iterate the array and return a new one with the returned result of a function

const b = a.map(f)

Iterates a and builds a new array with the result of executing f() on each a element

Filter an array

const b = a.filter(f)

Iterates a and builds a new array with elements of a that returned true when executing f() on each a element

Reduce

a.reduce((accumulator, currentValue, currentIndex, array) => {
    //...
}, initialValue)

reduce() executes a callback function on all the items of the array and allows to progressively compute a result. If initialValue is specified, accumulator in the first iteration will equial to that value.

Example:

[1,2,3,4].reduce((accumulator, currentValue, currentIndex, array) => {
    return accumulator * currentValue
}, 1)

// iteration 1: 1 * 1 => return 1
// iteration 2: 1 * 2 => return 2
// iteration 3: 2 * 3 => return 6
// iteration 4: 6 * 4 => return 24

// return value is 24

forEach

ES6

a.forEach(f)

Iterates f on a without a way to stop

Example:

a.forEach(v => {
    console.log(v)
})

for..of

ES6

for (let v of a) {
    console.log(v);
}

for

for (let i = 0; i < a.length; i += 1) {
    //a[i]
}

Iterates a, can be stopped using return or break and an iteration can be skipped using continue

@@iterator

ES6

Getting the iterator from an array returns an iterator of values

const a = [1, 2, 3]
let it = a[Symbol.iterator]();

console.log(it.next().value); //1
console.log(it.next().value); //2
console.log(it.next().value); //3

.entries() returns an iterator of key/value pairs

let it = a.entries();

console.log(it.next().value); //[0, 1]
console.log(it.next().value); //[1, 2]
console.log(it.next().value); //[2, 3]

.keys() allows to iterate on the keys:

let it = a.keys();

console.log(it.next().value); //0
console.log(it.next().value); //1
console.log(it.next().value); //2

.next() returns undefined when the array ends. You can also detect if the iteration ended by looking at it.next() which returns a value, done pair. done is always false until the last element, which returns true.

Adding to an array

Add a the end

a.push(4)

Add at the beginning

a.unshift(0)
a.unshift(-2, -1)

Removing an item from an array

From the end

a.pop()

From the beginning

a.shift()

At a random position

a.splice(0, 2); // get the first 2 items
a.splice(3, 2); // get the  2 items starting from index 3

Do not use remove() as it leaves behind undefined values.

Remove and insert in place

a.splice(2, 3, 2, 'a', 'b'); //removes 3 items starting from
                             //index 2, and adds 2 items,
                             // still starting from index 2

Join multiple arrays

const a = [1, 2]
const b = [3, 4]
a.concat(b) // 1, 2, 3, 4

Lookup the array for a specific element

a.indexOf()

Returns the index of the first matching item found, or -1 if not found

a.lastIndexOf()

Returns the index of the last matching item found, or -1 if not found

ES6

a.find((element, index, array) => {
    //return true or false
})

Returns the first item that returns true. Returns undefined if not found.

a.findIndex((element, index, array) => {
    //return true or false
})

Returns the index of the first item that returns true. Returns undefined if not found.

ES7

a.includes(value)

Returns true if a contains value.

a.includes(value, i)

Returns true if a contains value after the position i.

Get a portion of an array

a.slice()

Sort the array

Sort alphabetically (by ASCII value - 0-9A-Za-z)

const a = [1,2,3,10,11]
a.sort() //1, 10, 11, 2, 3

const b = [1,'a','Z',3,2,11]
b = a.sort() //1, 11, 2, 3, Z, a

Sort by a custom function

const a = [1,10,3,2,11]
a.sort((a, b) => a - b) //1, 2, 3, 10, 11

Reverse the order of an array

a.reverse()

Get a string representation of an array

a.toString()

Returns a string representation of an array

a.join()

Returns a string concatenation of the array elements. Pass a parameter to add a custom separator:

a.join(', ')

Copy an existing array by value

const b = Array.from(a)
const b = Array.of(...a)

Copy just some values from an existing array

const b = Array.from(a, x => (x % 2 == 0))

Copy portions of an array into the array itself, in other positions

const a = [1, 2, 3, 4]
a.copyWithin(0,2) // [3, 4, 3, 4]
const b = [1, 2, 3, 4, 5]
b.copyWithin(0,2) // [3, 4, 5, 4, 5]
                  //0 is where to start copying into,
                  // 2 is where to start copying from
const c = [1, 2, 3, 4, 5]
c.copyWithin(0, 2, 4) // [3, 4, 3, 4, 5]
                      //4  is an end index