JavaScript ES6 Arrays

Arrays are used to store collections of values in a sequential order. You can assign arrays to variables just like you can assign strings or any other data type. Arrays are useful for storing collections of elements where order is important.

let names = ["Steve", "Bob", "Sam", "Erick"]

names[0] //returns "Steve"
names[2] //returns "Sam"

Arrays start counting from 0. In the example above, "Steve" is the first element in the names array. When we call names[0], we are asking to return the element at position 0 of the array. This is why names[0] returns "Steve" and names[2] returns "Sam".

Defining Arrays

There are several ways to "create" or initialize arrays in JavaScript. The simplest way is to initialize an array within a variable definition. For example:

let scores = [87,43,88,99]

Arrays can also be created with the Array object:

let scores = new Array(87, 43, 88, 99)

Accessing Array Elements

Accessing elements in an array is easy. You simply provide the array name with the index you want to return:

let scores = [87,43,88,99]

scores[0] // returns 87
scores[1] // returns 43
scores[2] // returns 88

Looping Through Array Elements

To iterate through every element in an array, you can use the built in forEach() method.

let scores = [87,43,88,99]

scores.forEach((x) => {
  console.log(x)
})

//logs 87, 43, 88, 99

Other Array Methods

The forEach() method is one of many supported methods for JavaScript arrays. Following is a list of other methods with quick examples for each:

concat()

The concat() method combines arrays.

let scores = [87, 43, 88, 99]
let moreScores = [100,33,78,44]

scores.concat(moreScores)

//returns [87, 43, 88, 99, 100, 33, 78, 44]

every()

The every() method returns true if every element passes a given condition:

let scores = [87, 43, 88, 99]

scores.every((x) => { return x > 10 })

//returns true since every element is greater than 10

filter()

The filter() method returns a new array with every element that passes a filter function

let scores = [87, 43, 88, 99]

scores.filter((x) => { return x > 80 })

//returns [87, 88, 99]

indexOf()

This method returns the first element of an array that matches the given value. If no element matches the value, -1 is returned:

let scores = [87, 43, 88, 99]

scores.indexOf(88) //returns 2
scores.indexOf(103) // returns -1

join()

The join() method combines all of the elements of an array into a string.

let scores = [87, 43, 88, 99]

scores.join() //returns "87,43,88,99"
scores.join("|") //returns "87|43|88|99"

lastIndexOf()

Similar to indexOf, but returns the index of the last element that matches the provided value. Returns -1 if there is no match:

let scores = [87, 43, 88, 99, 88]

scores.lastIndexOf(88) //returns 4
scores.lastIndexOf(11) //returns -1

map()

The map() function applies a code block or function to each element in the array and returns a new array with the results of each operation.

let scores = [87, 43, 88, 99]

scores.map((x) => {return x + 10})

//returns [97, 53, 98, 109]

pop()

The pop() method removes the last element in an array and returns that element.

let scores = [87, 43, 88, 99]

scores.pop() //returns 99

//scores now equals [87, 43, 88]

push()

The push() method adds a new element to the array and returns the array's new length

let scores = [87, 43, 88, 99]

scores.push(44) //returns 5

//scores now equals [87, 43, 88, 99, 44]

reduce()

The reduce() method returns an aggregated result of a function applied to the array

let count = [1,2,3,4]

count.reduce((a,b) => {return a + b})

//returns 10

reduceRight()

Same as reduce(), but operates from right to left:

let count = [1,2,3,4]

count.reduceRight((a,b) => {return a - b})

//returns -2

reverse()

Reverses the elements in an array:

let scores = [87, 43, 88, 99]

scores.reverse()

//returns [99, 88, 43, 87]

shift()

The shift() method is like pop() but acts on the first element in the array rather than the last.

let scores = [87, 43, 88, 99]

scores.shift() //returns 87

//scores now equals [43, 88, 99]

slice()

Returns a subarray based on a start and end position:

let scores = [87, 43, 88 99]

scores.slice(1,3)

//returns [43,88]

some()

The some() method retuns true if at least one element meets the given condition

let scores = [87, 43, 88, 99]

scores.some((x) => {return x < 50}) //returns true
scores.some((x) => {return x < 40}) //returns false

sort()

Sorts the elements of an array:

let scores = [87, 43, 88, 99]

scores.sort() //returns [43, 87, 88, 99]
scores.sort((a,b) => {return b - a}) // returns [99, 88, 87, 43]

splice()

The splice() method changes the content of an array. This method takes three arguments: (starting index, number of elements to remove, replacement elements)

let scores = [87, 43, 88, 99]

scores.splice(2, 0, 95) //returns []

//scores now equals [87, 43, 95, 88, 99]

let counts = [1, 2, 3, 4, 5]

counts.splice(1, 3) //returns [2,3,4]

//scores now equals [1,5]

Note that if we omit the third argument, splice() simply removes the elements from the array. It's also important to recognize that splice() returns the elements removed and alters the existing array.

toString()

Simply converts the array to a string.

let scores = [87, 43, 95, 88, 99]

scores.toString()

//returns '87,43,95,88,99'

unshift()

Adds elements to the beginning of the array and returns the new array length.

let scores = [87, 43, 95, 88, 99]

scores.unshift(50,70) //returns 7

//scores now equals [50, 70, 87, 43, 95, 88, 99]

find()

The find()method returns the first element that matches a specified condition.

let scores = [87, 43, 95, 88, 99]

scores.find((x) => {return x > 90})

//returns 95

findIndex()

Same as find() but returns the first index instead of the first value that meets the condition.

let scores = [87, 43, 95, 88, 99]

scores.findIndex((x) => {return x > 90})

//returns 2

entries()

The entries() function returns an iterator that can be used to loop through the array's keys and values

let scores = [87, 43, 95, 88, 99]

var entries = scores.entries()

console.log(entries.next().value) //returns [0, 87]
console.log(entries.next().value) //returns [1, 43]

from()

The from() method creates a new array from an array-like object.

let nameArray = Array.from('Sam')

console.log(nameArray)

//logs ['S', 'a', 'm']

keys()

The keys() method returns a new iterator object that contains the keys for each index in the array.

let scores = [87, 43, 95, 88, 99]
let iterator = scores.keys();

console.log(iterator.next())

//logs {value: 0, done: false}

Conclusion

Arrays are powerful data types in JavaScript. Use arrays when you want to keep track of a collection of items and order matters.

Your thoughts?