Skip to main content

Array Methods

split() and join() methods

The split(delimiter) method converts a string to an array by “splitting” it with delimiter. If the delimiter is an empty string, you get an array of individual characters. The separator can be one or more characters.

const name = "Mango";
console.log(name.split("")); // ["M", "a", "n", "g", "o"]

const message = "JavaScript is awesome";
console.log(message.split(" ")); // ["JavaScript", "is", "awesome"]

The join(delimiter) array method joins the elements of an array into a string. In a string, elements will be delimited by a character or a group of characters specified in delimiter. That is, it is the opposite of the split(delimiter) string method.

const words = ["JavaScript", "is", "awesome"];
console.log(words.join("")); // "JavaScriptisawesome"
console.log(words.join(" ")); // "JavaScript is awesome"
console.log(words.join("-")); // "JavaScript-is-awesome"

indexOf() method

indexOf(value) returns the first index at which the element with value is found in the array, or the number 1 if there is no such element. Use indexOf when you need to get the index of an element.

const clients = ["Mango", "Ajax", "Poly", "Kiwi"];
console.log(clients.indexOf("Poly")); // 2
console.log(clients.indexOf("Monkong")); // -1

includes() method

includes(value) checks if there is an element with value in the array, and it returns true or false. This method is used in situations where you need to check whether there is an element in the array, and its position (index) is not important.

const clients = ["Mango", "Ajax", "Poly", "Kiwi"];
console.log(clients.includes("Poly")); // true
console.log(clients.includes("Monkong")); // false

Checking multiple conditions with includes()

At first glance, the code in the following example looks good.

const fruit = "apple";

if (fruit === "apple" || fruit === "strawberry") {
console.log("It is a red fruit!");
}

However, what if you have more red fruits, like more cherries or cranberries? Are you going to expand the condition with an additional ||?

const fruit = "apple";

if (
fruit === "apple" ||
fruit === "strawberry" ||
fruit === "cherry" ||
fruit === "cranberries"
) {
console.log("It is a red fruit!");
}

You can rewrite the condition using the includes() method, which is very simple and scalable.

// Make an array of options
const redFruits = ["apple", "strawberry", "cherry", "cranberries"];
const fruit = "cherry";
// Check if the element exists
const hasFruit = redFruits.includes(fruit);

if (hasFruit) {
console.log(`${fruit} is a red fruit!`);
}

push() and pop() methods

These add or remove elements at the beginning/end of arrays. They apply only to the leftmost and rightmost element and cannot add or remove an element in an arbitrary position.

array methods

The push() method adds one or more elements to the end of the array, without the need to specify the indices of the added elements. It returns the array length after adding.

push method
const numbers = [];

numbers.push(1);
console.log(numbers); // [1]

numbers.push(2);
console.log(numbers); // [1, 2]

numbers.push(3);
console.log(numbers); // [1, 2, 3]

numbers.push(4);
console.log(numbers); // [1, 2, 3, 4]

numbers.push(5);
console.log(numbers); // [1, 2, 3, 4, 5]

The pop() method removes the last element from the end of the array and returns the removed element. If the array is empty, it returns undefined.

pop method
const numbers = [1, 2, 3, 4, 5];

console.log(numbers.pop()); // 5
console.log(numbers); // [1, 2, 3, 4]

console.log(numbers.pop()); // 4
console.log(numbers); // [1, 2, 3]

console.log(numbers.pop()); // 3
console.log(numbers); // [1, 2]

console.log(numbers.pop()); // 2
console.log(numbers); // [1]

console.log(numbers.pop()); // 1
console.log(numbers); // []

slice() method

slice(begin, end) returns a new array containing a partial copy of the original array without changing it. It makes a copy from begin to, but not including, end, i.e. the indices of elements from the original array.

slice method
const clients = ["Mango", "Ajax", "Poly", "Kiwi"];
console.log(clients.slice(1, 3)); // ["Ajax", "Poly"]

If begin and end are not specified, a complete copy of the original array will be created.

const clients = ["Mango", "Ajax", "Poly", "Kiwi"];
console.log(clients.slice()); // ["Mango", Ajax", "Poly", "Kiwi"]

If end is not specified, copying will be from start to the end of the original array.

const clients = ["Mango", "Ajax", "Poly", "Kiwi"];
console.log(clients.slice(1)); // ["Ajax", "Poly", "Kiwi"]
console.log(clients.slice(2)); // ["Poly", "Kiwi"]

If start is negative and end is not specified, the last start elements will be copied.

const clients = ["Mango", "Ajax", "Poly", "Kiwi"];
console.log(clients.slice(-2)); // ["Poly", "Kiwi"]

splice() method

The Swiss Army knife for working with arrays when the original array needs to be changed. It removes, adds and replaces elements anywhere in the array.

Removal

To remove array elements, two arguments should be used.

splice(position, num)
  • position indicates the position (index) of the first element to be removed
  • num indicates the number of elements to be removed

The splice method modifies the original array and returns an array containing the removed elements. For example, you have an array of scores that contains five numbers, from 1 to 5.

const scores = [1, 2, 3, 4, 5];

// Remove three array elements, starting with the first one (index 0)
const deletedScores = scores.splice(0, 3);

// The scores array now contains two elements
console.log(scores); // [4, 5]

// The deletedScores array contains three deleted elements
console.log(deletedScores); // [1, 2, 3]

The figure shows calling the score.splice(0, 3) method from the example.

splice remove
Note

In practice, the returned value (array of deleted elements) is rarely used. Most of the time, you just need to remove some array elements.

Addition

In order to add one or more elements to the array, you need to pass three or more arguments, with the second argument equal to zero.

splice(position, 0, new_element_1, new_element_2, ...)
  • The position argument specifies the starting position in the array where new elements will be inserted.
  • The second argument is zero; it instructs the method not to remove elements where new ones are added.
  • The third, fourth and all subsequent arguments are new elements that are added to the array.

For example, you have an array of color names as strings. Add a new color before the element with index 2.

const colors = ["red", "green", "blue"];

colors.splice(2, 0, "purple");
console.log(colors); // ["red", "green", "purple", "blue"]

The figure shows calling the colors.splice(2, 0, 'purple') method from the example.

splice insert

You can add as many elements as you want by passing the fourth, fifth argument, etc.

const colors = ["red", "green", "blue"];

colors.splice(1, 0, "yellow", "pink");
console.log(colors); // ["red", "yellow", "pink", "green", "blue"]

Replacement

Replacement is an addition in which elements are removed where new ones are added. To do this, you need to pass at least three arguments. The number of items removed and added may be different.

splice(position, num, new_element_1, new_element_2, ...)
  • position indicates the position (index) of the first element to be removed
  • num determines the number of elements to be removed
  • The third, fourth and all subsequent arguments are new elements that are added to the array

For example, you have an array of programming languages of four elements.

const languages = ["C", "C++", "Java", "JavaScript"];

// Replace the element with index 1 with a new one
languages.splice(1, 1, "Python");
console.log(languages); // ["C", "Python", "Java", "JavaScript"]

// Replace one element (with index 2) with several ones
languages.splice(2, 1, "C#", "Swift", "Go");
console.log(languages); // ["C", "Python", "C#", "Swift", "Go", "JavaScript"]

The figure shows calling the languages.splice(1, 1, 'Python') method from the example.

splice replace

concat() method

This consolidates two or more arrays into one. It does not change the original array, but returns a new one. The order of method arguments affects the order of elements in the new array.

const oldClients = ["Mango", "Ajax", "Poly", "Kiwi"];
const newClients = ["Monkong", "Singu"];

const allClientsWithOldFirst = oldClients.concat(newClients);
console.log(allClientsWithOldFirst); // ["Mango", "Ajax", "Poly", "Kiwi", "Monkong", "Singu"]

const allClientsWithNewFirst = newClients.concat(oldClients);
console.log(allClientsWithNewFirst); // ["Monkong", "Singu", "Mango", "Ajax", "Poly", "Kiwi"]

console.log(oldClients); // ["Mango", "Ajax", "Poly", "Kiwi"]
console.log(newClients); // ["Monkong", "Singu"]