Here’s a reference type of post on modifying arrays with native JavaScript methods.
Adding to the end of arrays with .push()
Put anything into an array:
let a = []
let b = {}
a.push(b)
console.log(a[0] === b) // trueAdd more than one item at a time:
let x = ['a']
x.push('b', 'c')
console.log(x) // ['a', 'b', 'c']Add to the beginning of array with .unshift()
Add items to the beginning of an array:
let x = ['c', 'd']
x.unshift('a', 'b')
console.log(x) // ['a', 'b', 'c', 'd']Combine arrays with .push.apply() and .concat()
Add the contents of one array to another:
let x = ['a', 'b', 'c']
let y = ['d', 'e', 'f']
x.push.apply(x, y)
console.log(x) // ['a', 'b', 'c', 'd', 'e', 'f']
console.log(y) // ['d', 'e', 'f']Create a new array from two arrays:
let x = ['a', 'b', 'c']
let y = ['d', 'e', 'f']
let z = x.concat(y)
console.log(x) // ['a', 'b', 'c']
console.log(y) // ['d', 'e', 'f']
console.log(z) // ['a', 'b', 'c', 'd', 'e', 'f']Splicing arrays with .splice()
Replace an arbitrary item in array with splice(). The 3 params of splice are:
- Position
- How many items to remove
- What do add
let a = [1, 2, 3, 4]
a.splice(2, 1, 'foo')
console.log(a) // [1, 2, "foo", 4]Add an arbitrary node to array with splice():
let a = [1, 2, 3, 4]
a.splice(2, 0, 'foo')
console.log(a) // [1, 2, "foo", 3, 4]Removing nodes from an array
Remove the first item from an array:
let a = [1, 2, 3, 4]
a.pop()
console.log(a) // [2, 3, 4]Remove the last item from an array:
let a = [1, 2, 3, 4]
a.shift()
console.log(a) // [2, 3, 4]Remove an arbitrary element from array with splice(). If you skip the 3rd
parameter splice can be used to remove items:
let a = [1, 2, 3, 4]
a.splice(1, 1)
console.log(a) // [1, 3, 4]Reverse an array with .reverse()
let a = [1, 2, 3, 4]
a.reverse()
console.log(a) // [4, 3, 2, 1]Sorting arrays with .sort()
Sort an array alphabetically, this is the default behavior of
Array.prototype.sort(). For sorting by a separate preferred order, see
sorting an array with another array:
let a = ['d', 'j', 'a', 'b', 'c', 'g']
a.sort()
console.log(a) // ["a", "b", "c", "d", "g", "j"]Sort array in reversed alphabetical order, sort it first then reverse:
let a = ['d', 'j', 'a', 'b', 'c', 'g']
a.sort().reverse()
console.log(a) // [ "j", "g", "d", "c", "b", "a"]Ascending numerical sort. If the below array a was sorted alphabetically, 10
would come second, not last:
let a = [5, 10, 7, 1, 3, 2]
a.sort((a, b) => {
return a - b
})
console.log(a) // [ 1, 2, 3, 5, 7, 10]Descending numerical sort, revert the a and b:
let a = [5, 10, 7, 1, 3, 2]
a.sort((a, b) => {
return b - a
})
console.log(a) // [10, 7, 5 ,3, 2, 1]Sort by string length:
let a = ['hi', 'hello', 'bonjour', 'moi', 'hola', 'hoi', 'moin']
a.sort((a, b) => {
return a.length - b.length
})
console.log(a) // ["hi", "moi", "hoi", "hola", "moin", "hello", "bonjour"]