Array Manipulation in JavaScript

Rianna Cleary
6 min readJan 28, 2020

--

Descriptions on basic array manipulations and how they affect data types in JS.

Array manipulation allows you to do tasks such as add, remove, or transform elements in your array. There are countless methods that you can call on arrays to manipulate them, and they fall into two categories which are destructive and non-destructive. Destructive methods change your array in memory so you won’t have your original copy, while as non-destructive methods produce a copy of your original array, just manipulated.

Manipulation

Destructive Manipulation Methods

.push()

The .push() method is used for appending (fancy word for adding) an element to the end of an array. The return value is the new of the array in which you pushed the new value.

let evens = [2,4,6,8]
evens.push(10)
// => 5
console.log(evens)
// => [2,4,6,8,10]

.unshift()

The .unshift() method is used for appending an element to the beginning of an array. Think of it as basically shifting all of the elements over in order to squeeze in another. The return value is also the new length of the array.

let fruits = ['apple', 'orange', 'banana']
fruits.unshift('kiwi')
// => 4
console.log(fruits)
// => ['kiwi', 'apple', 'orange', 'banana']

.pop()

The .pop() method removes an element from the end of an array. The return value is the element that was removed.

let odds = [1,3,5,7]
numbers.pop()
// => 7
console.log(odds)
// => [1,3,5]

.shift()

The .shift() method removes an element from the beginning of an array. Similar to .unshift() , this method also shifts all of the elements, but in the opposite direction. The return value is also the element that was removed.

let animals = ['lions', 'tigers', 'bears']
animals.shift()
// => 'lions'
console.log(animals)
// => ['tigers', 'bears']

.splice()

.splice() is a method that not only removes elements but could also add them to the array itself. It is required that .splice() takes in one argument, which is the starting position to add/remove elements. Although .splice() needs one required argument, it accepts other optional arguments. The return value of calling .splice() on an array with one argument is element that was spliced. The optional arguments give you the ability to cut out a part of the array or place one or more elements at a specific index.

let seaCreatures = ['whale', 'seahorse', 'shark', 'eel', 'dolphin']
seaCreatures.splice(2)
// => ['shark', 'eel', 'dolphin']
console.log(seaCreatures)
// => ['whale', 'seahorse']

The other arguments after that are optional, but if you want to add to an array than those arguments are needed. The second argument tells .splice() how many of those elements you want to remove. If you want to add elements, you just specify what element you want to add afterward in place of the arguments that were removed.

let seaCreatures = ['whale', 'seahorse', 'shark', 'eel', 'dolphin']
seaCreatures.splice(1,3)
// => ['seahorse', 'shark', 'eel']
console.log(seaCreatures)
// => ['whale', 'dolphin']
// to add to array //seaCreatures.splice(1,3,'jellyfish', 'squid')
// => ['seahorse', 'shark', 'eel']
console.log(seaCreatures)
// => ['whale', 'jellyfish', 'squid', 'dolphin']

Although these methods are great and simple to use for array manipulations, they are also destructive, which is not always what you want in your code. For example, what if you want to manipulate an array, but still leave the value of the original array unchanged? Below are types of manipulations that are a bit more complex, but will leave your original array unchanged!

Non-destructive Manipulation Methods

.slice()

The .slice() method does just as it implies; it takes a section of the array and slices it, leaving you with your original and a copy of the updated array, both of which point to two different objects in memory. Unlike the destructive methods .pop() and .shift() , .slice() takes in parameters. You can call .slice() on an array without any parameters, however, it will only return a new array object. You can also declare your array variable as a const instead of a let because we won’t be manipulating the original array.

const myGuiltyPleasures = ['pizza', 'icecream', 'cookies']
myGuiltyPleasures2.slice() // => ['pizza', 'icecream', 'cookies']
console.log(myGuiltyPleasures)
// => ['pizza', 'icecream', 'cookies']

.slice() takes in two parameters, a start, and an end. The starting parameter is the index in which you want to start parsing. The second parameter is the index where you want the parse to end, though it will not include that element in the new array. For example:

const planets = ['Saturn', 'Jupiter', 'Neptune', 'Venus', 'Earth']
planets2 = planets.slice(1,4)
// => ['Jupiter', 'Neptune', 'Venus']
console.log(planets)
// => ['Saturn', 'Jupiter', 'Neptune', 'Venus', 'Earth']

Here we started at arr6[1] which in this case was the string ‘jupiter’ and ended but didn’t include, at arr6[4] which was the string 'earth'.

.filter()

.filter() is a removal method that filters through the given array based on a condition. The first parameter it takes in is a function. Whenever you refer to a function that’s being passed on as an argument try to refer to it as a “callback function”. The second parameter is optional which is its thisValue.The this keyword is a whole other ballpark that we won’t cover today. For now, let’s just focus on the function argument. The function itself takes in three arguments: the currentValue of the element (required), the index of the current element, and the array object the element belongs to. For instance, if we had an array of strings and wanted to return a new array that contained all of the strings that started with the letter ‘A’, we could do something like:

const foods = ['apple', 'pizza', 'chocolate', 'arugula', 'avocados']function foodsThatStartWithA(food) {
let i = 0
return food[i] === 'a'
}
foods.filter(foodsThatStartWithA)
// => ['apples', 'arugula', 'avocados']
console.log(foods)
// => ['apple', 'pizza', 'chocolate', 'arugula', 'avocados']

.concat()

The non-destructive method for adding an element to an array is .concat(). With .concat() , you could add an element to the end of an array like so:

const sweets = ['milky-way', 'twix', 'kit-kat', 'hershey-bar']
sweets.concat('snickers')
// => ['milky-way', 'twix', 'kit-kat', 'hershey-bar', 'snickers']

Another method is called the spread operator, which are three dots ... that are added to the beginning of the array variable.

const sweets = ['milky-way', 'twix', 'kit-kat', 'hershey-bar']const gimmeMoreSweets = [...sweets, 'snickers']
console.log(gimmeMoreSweets)
// => ['milky-way', 'twix', 'kit-kat', 'hershey-bar','snickers']
const gimmeEvenMoreSweets = ['m&m\'s', ...sweets]
console.log(gimmeEvenMoreSweets)
// => ['m&m\'s', 'milky-way', 'twix', 'kit-kat', 'hershey-bar']

.map()

The last method I am going to cover is .map(). You can utilize this method if you want to transform the data in your array. Its parameters are similar to .filter(), the difference is that .map() will transform your data and returns the same number of elements that were in the original array, while as .filter() returns the array based on if the functionality you passed in is true or not.

const sodas = ['Coca-Cola', 'Pepsi', 'Sprite', 'Cream soda']
sodas.map(soda => {
let i = 0
if (soda[i] === 'C') {
soda = 'Dr. Pepper';
}
return soda
})
// => ['Dr. Pepper', 'Pepsi', 'Sprite', 'Dr. Pepper']
console.log(sodas)
// => ['Coca-Cola', 'Pepsi', 'Sprite', 'Cream soda']

You could use very complex functions/conditions with .map() , this is just using it with a basic condition.

Non-destructive vs Destructive

Non-destructive methods are safer than destructive methods in the sense that you’re always going to have the original copy of the array you’re changing. Let’s say you’re building an app and you have a bunch of array objects. As your application grows your data will grow, and you will probably have to manipulate those arrays more often. It is always guaranteed that using non-destructive methods will always keep your original array unchanged.

Below are links that go more in-depth about what these methods can do along with other manipulation methods you can try!

--

--