JavaScript Array Type

Insertion

We can use the push method to insert elements at the end or unshift to insert elements at the start of the array.

const metals = ["Iron", "Steel", "Tin"]
metals.push("Pewter")
console.log(metals) // ["Iron", "Steel", "Tin", "Pewter"]
metals.unshift("Zinc", "Brass")
console.log(metals) // ["Zinc", "Brass", "Iron", "Steel", "Tin", "Pewter"]

Notice how these methods mutate the array instead of returning a completely new array.

Functional insertion

There are a couple of ways we can insert elements into an array without modifying it directly but rather create an entirely new array.

Spread operator

The three dots ... is called a spread operator and expands arrays (or other iterable types). It does this by creating copies of the original arrays and as a result we get new array instances.

const a = [1, 2, 3]
const b = [...a, 4]
const c = [5, 6, ...a]
console.log(a) // [1, 2, 3]
console.log(b) // [1, 2, 3, 4]
console.log(c) // [5, 6, 1, 2, 3]

Array c is proof that the spread operator does not mutate the array operands its given.

Concatenation

The concat method can be used to merge two or more arrays without mutating the existing arrays.

const a = [1, 2, 3]
const b = a.concat([4])
const c = [5, 6].concat(a)
console.log(a) // [1, 2, 3]
console.log(b) // [1, 2, 3, 4]
console.log(c) // [5, 6, 1, 2, 3]

Test yourself

Description

Define a new function with the name

twoMore

that takes an integer array input parameter scores and returns a new array with one element inserted at the start and one element inserted at the end.

The element inserted at the start should be a number one lower than the first element of the input array. The element inserted at the end should be a number one higher than the last element of the input array.

Your function should not mutate the input array, but rather return a new array instance with the two additinal elements.

Assumptions:

  • The input array has at least one element.
  • All elements of the input array are integer numbers.

Tests

  1. 1 You should define a function named twoMore.
  2. 2twoMore([1]) should return [0,1,2].
  3. 3twoMore([100,200,300]) should return [99,100,200,300,301].
Editor