DEV Community

Cover image for 10 most used Javascript Array methods
zuzexx
zuzexx

Posted on

10 most used Javascript Array methods

Array is a single variable that is used to store different elements. It is mostly used when we want to store a list of elements and access them, using one variable. Storing elements into an array enables us to perform unique methods and operations on those items.

In Javascript arrays are Array objects with the following characteristics:

  • Javascript arrays are resizable and can contain a mix of different data types.
  • Javascript arrays are zero-indexed, which means that the first item in an array will always have index 0.
  • When using array-copy operations on a javascript array the operation creates a shallow copy. That means that the source and the copy are not completely independent and changing one can cause changes in the other.

To work with arrays methods are used, which enable us to manipulate arrays in different ways. Here are some of the methods that are used on arrays a lot.

Table of Contents

  1. .push()
  2. .pop()
  3. .unshift()
  4. .shift()
  5. .splice()
  6. .slice()
  7. .concat()
  8. .indexOf()
  9. .lastIndexOf()
  10. .toString()

.push()

.push() adds one or more elements to the end of the array and returns the new length of the array.

Syntax

push(element0, element1, /* … ,*/ elementN)
Enter fullscreen mode Exit fullscreen mode

elementN -> element/s that will be added to the end of the array

Examples

// adding elements to the array
const animals = ["dog", "cat"];
const pushedArray = animals.push("fish", "horse");

console.log(animals); 
console.log(pushedArray); 

/*
Expected output:
animals = ["dog", "cat", "fish", "horse"]
pushedArray = 4 -> length of the new array
*/
Enter fullscreen mode Exit fullscreen mode
// merging two arrays
const animals = ["dog", "cat"];
const moreAnimals = ["fish", "horse", "hippo"]

const pushed1 = animals.push(moreAnimals)
const pushed2 = animals.push(...moreAnimals)

console.log(pushed1); 
console.log(pushed2); 

/*
Expected output:
pushed1 = ["dog", "cat", ["fish", "horse", "hippo"]]
pushed2 = ["dog", "cat", "fish", "horse", "hippo"]
*/
Enter fullscreen mode Exit fullscreen mode

Instead of using .push()you can use .concat()method to merge two arrays


.pop()

.pop() removes the last element of an array. It returns the removed value or undefined if the original array has no elements.

Syntax

pop()
Enter fullscreen mode Exit fullscreen mode

Example

const vegetables = ['broccoli', 'cauliflower', 'cabbage'];

console.log(vegetables.pop())

/*
Expected output:
"broccoli" -> is removed from the original array
2 -> length of the new array
*/

Enter fullscreen mode Exit fullscreen mode

.unshift()

.unshift() adds one or more elements to the beginning of the array. If multiple elements are passed as parameters, they are inserted at the beginning in the exact same order they were passed as parameters.

Syntax

unshift(element0, element1, /* … ,*/ elementN)
Enter fullscreen mode Exit fullscreen mode

elementN -> elements that will be added to the front of the array

Example

const array = ["My", "name", "is", "Neo", "."]

array.unshift("Hello", "World", "!")

console.log(array)

/*
Expected output: 
["Hello", "World", "!", "My", "name", "is", "Neo", "."]
*/
Enter fullscreen mode Exit fullscreen mode

.shift()

.shift() removes the first element of an array and returns the removed item. It changes the lenght of the original array. If the original array has no items (length is 0) then the method returns undefined.

Syntax

shift()
Enter fullscreen mode Exit fullscreen mode

Example

const array = ["My", "name", "is", "Neo"]
const firstElement = array.shift()

console.log(array)
console.log(firstElement)

/*
Expected output:
array = ["name", "is", "Neo]
fristElement = ["My"]
*/

Enter fullscreen mode Exit fullscreen mode

.splice()

.splice() is used to change the contents of an array by removing or replacing elements in the array. Elements can also be added using .splice(). This method returns an array containing the deleted elements. If no elements are removed, then an empty array is returned.

Syntax

splice(start, deleteCount, item1, item2,/*...*/ ,itemN)
Enter fullscreen mode Exit fullscreen mode

start -> a zero-based index at witch the methods starts changing the array. If a negative value is used, then the method counts back from the end of the array (if start < 0 then the array starts changing at start + array.length. If this value is omitted than the value 0is used by the method. If the start walue is bigger than the lenght of the array then nothing will change with the array (no item will be deleted/replaced), but the method will behave as an adding function as many elements as provided.
deleteCount -> an integer indicating the number of elements in the array to remove from start. If deleteCountis omitted, or it's value is greater than the number of elements from startto the end of the array, then all of the elements starting from start will be deleted. If the deleteCount value is less or the same as 0, no items will be removed and an itemN value should be passed, because an item will be added.
itemN -> element/s added to the array, beginning at start

Examples

//remove 0 elements - insert 2 elements
const animals = ["cat", "fish", "dog", "bird"];
const splicedArray = animals.splice(3, 0, "horse", "elephant");

console.log(splicedArray)

/*
Expected result: 
animals = ["cat", "fish", "dog", "horse", "elephant", "bird"]
Returned value: [] - no items are removed
*/
Enter fullscreen mode Exit fullscreen mode
//remove 1 element
const animals = ["cat", "fish", "dog", "bird"];
const splicedArray = animals.splice(2, 1);

console.log(splicedArray)

/*
Expected result: 
animals = ["cat", "fish", "bird"]
Returned value: ["dog"] - removed item at index value 2
*/
Enter fullscreen mode Exit fullscreen mode
//remove 1 element - insert 2 elements
const animals = ["cat", "fish", "dog", "bird"];
const splicedArray = animals.splice(2, 1, "horse", "elephant");

console.log(splicedArray)

/*
Expected result: 
animals = ["cat", "fish", "horse", "elephant", "bird"]
Returned value: ["dog"] - removed item at index value 2
*/
Enter fullscreen mode Exit fullscreen mode
//remove all elements from specified index
const animals = ["cat", "fish", "dog", "bird"];
const splicedArray = animals.splice(2);

console.log(splicedArray)

/*
Expected result: 
animals = ["cat", "fish"]
Returned value: ["dog", "bird"] 
- removed items from index 2 untill the end
*/
Enter fullscreen mode Exit fullscreen mode

.slice()

.slice() returns a shallow copy od a portion of an array, based on the start and end values specified. The original array is not modified in the process. This method preserves empty slots from the original array.

Syntax

slice(start, end)
Enter fullscreen mode Exit fullscreen mode

Parameters start and end are both optional.
start-> zero-based index at which the extraction of the elements starts. If start value is larger than the length of the array then nothing is extracted.
end -> zero-based index at which the extraction ends. if end < 0 then end + array.length is used. If end >= array.length or the end is ommited than all of the items from the start untill the end of the array are deleted. If end is positioned before the start then nothing is deleted.

Example

//return a portion of an existing array

const fruits = ["banana", "apple", "cucumber", "salad", "watermelon"]
const sus = fruits.slice(2,4)

/*
Expected result:
fruits = ["banana", "apple", "cucumber", "salad", "watermelon"]
sus = ["cucumber", "salad"]
*/
Enter fullscreen mode Exit fullscreen mode

.concat()

.concat() is used to merge multiple arrays. It is a copying method, therefore it does not change the existing arrays, but instead returns a shallow copy, that contains the same elements as the original arrays. It preserves empty slots from the original arrays.

Syntax

concat(value0, value1, /* … ,*/ valueN)
Enter fullscreen mode Exit fullscreen mode

valueN -> arrays and/or values to concatinate into a new array. If no valueN parameter is specified the method returns a shallow copy of the array on which it is called.

Examples

// concatinating no arrays
const array = [1,2,3,4,5,6,7,8,9,10]
const concatArray = array.concat()

console.log(concatArray)

/*
Expected output: [1,2,3,4,5,6,7,8,9,10]
*/

Enter fullscreen mode Exit fullscreen mode
// concatinating two arrays
const array1 = ["Hello"]
const array2 = ["World", "!"]
const concatArray = array1.concat(array2)

console.log(concatArray)

/*
Expected output: ["Hello", "World", "!"]
*/

Enter fullscreen mode Exit fullscreen mode
// concatinating three arrays
const array1 = [1,2,3]
const array2 = ["Hello","World", "!"]
const array3 = [3,2,1]
const concatArray = array1.concat(array2, array3)

console.log(concatArray)

/*
Expected output: [1,2,3,"Hello", "World", "!",3,2,1]
*/

Enter fullscreen mode Exit fullscreen mode

.indexOf()

The indexOf() method returns the first index at which a given element can be found in the array, or -1 if it is not present. The array is searched from the beginning, starting at fromIndex.

Syntax

indexOf(searchElement, fromIndex)
Enter fullscreen mode Exit fullscreen mode

searchElement-> element to locate in the array.
fromIndex -> zero-based index at which the start of the search for the element begins. The search starts from the beginning of the array and runs to the end or when the element is found.

Example

const numbers = [1, 6, 3, 5];

numbers.lastIndexOf(1);
numbers.lastIndexOf(3);
numbers.lastIndexOf(7);

/*
Expected result:
numbers.lastIndexOf(1) -> 0
numbers.lastIndexOf(3) -> 2
numbers.lastIndexOf(7) -> -1
*/

Enter fullscreen mode Exit fullscreen mode

.lastIndexOf()

The lastIndexOf() method returns the last index at which a given element can be found in the array, or -1 if it is not present. The array is searched backwards, starting at fromIndex.

Syntax

lastIndexOf(searchElement, fromIndex)
Enter fullscreen mode Exit fullscreen mode

searchElement-> element to locate in the array.
fromIndex -> zero-based index at which the start of the search for the element begins. The search starts from the end of the array and runs to the beginning or when the element is found.

Example

const numbers = [2, 7, 3, 2];

numbers.lastIndexOf(2);
numbers.lastIndexOf(7);
numbers.lastIndexOf(9);

/*
Expected result:
numbers.lastIndexOf(2) -> 3
numbers.lastIndexOf(7) -> 1
numbers.lastIndexOf(9) -> -1
*/


Enter fullscreen mode Exit fullscreen mode

.toString()

.toString() returns a string representing the elements of the array called on. It calls the .join() method internaly, which joins the array abd returns one string containing each array element, separated by commas.

Syntax

.toString()
Enter fullscreen mode Exit fullscreen mode

Example

const array = [1, "Hello", "my", 2, "name", 3, 4, "is Neo", 5]

console.log(array.toString())

/*
Expected output: "1,Hello,my,2,name,3,4,is Neo,5"
*/
Enter fullscreen mode Exit fullscreen mode

These are some of the methods used the most when it comes to working with arrays. There are however many more methods, that I did not write about here, but will talk about in the future.

Top comments (0)