DEV Community

Cover image for 15+ Array Methods in Javascript
Tabassum Khanum
Tabassum Khanum

Posted on • Edited on

15+ Array Methods in Javascript

What is Array in JS?

The Array object, as with arrays in other programming languages, enables storing a collection of multiple items under a single variable name, and has members for performing common array operations.

Declaring arrays

We can declare arrays in two different ways.

Using new Array

With new Array, we could specify the elements we want to exist within the array, like this:

const fruits = new Array('Apple', 'Banana');
console.log(fruits.length);
Enter fullscreen mode Exit fullscreen mode

Array literal notation

Declaring with an array literal, we specify the values that the array will have. If we don’t declare any values, the array will be empty.

// 'fruits' array created using array literal notation.
const fruits = ['Apple', 'Banana'];
console.log(fruits.length);
Enter fullscreen mode Exit fullscreen mode

Javascript Array Methods

Here is a list of the methods of the Array object along with their description.

1.forEach

The forEach() method executes a provided function once for each array element.

forEach() calls a provided callbackFn function once for each element in an array in ascending index order. It is not invoked for index properties that have been deleted or are uninitialized.

array.forEach(callback[, thisObject]);
Enter fullscreen mode Exit fullscreen mode
const array1 = ['a', 'b', 'c'];

array1.forEach(element => console.log(element));

// expected output: "a"
// expected output: "b"
// expected output: "c"
Enter fullscreen mode Exit fullscreen mode

2.map

The Array.map() method allows you to iterate over an array and modify its elements using a callback function. The callback function will then be executed on each of the array's elements.

array.map(callback[, thisObject]);
Enter fullscreen mode Exit fullscreen mode
let arr = [3, 4, 5, 6];

let modifiedArr = arr.map(function(element){
    return element *3;
});

console.log(modifiedArr); // [9, 12, 15, 18]
Enter fullscreen mode Exit fullscreen mode

The Array.map() method is commonly used to apply some changes to the elements, whether multiplying by a specific number as in the code above, or doing any other operations that you might require for your application.

3.concat

In JavaScript, concat() is a string method that is used to concatenate strings together. The concat() method appends one or more string values to the calling string and then returns the concatenated result as a new string. Because the concat() method is a method of the String object, it must be invoked through a particular instance of the String class.

array.concat(value1, value2, ..., valueN);
Enter fullscreen mode Exit fullscreen mode
const array1 = ['a', 'b', 'c'];
const array2 = ['d', 'e', 'f'];
const array3 = array1.concat(array2);

console.log(array3);
// expected output: Array ["a", "b", "c", "d", "e", "f"]
Enter fullscreen mode Exit fullscreen mode

4.push

Javascript array push() method appends the given element(s) in the last of the array and returns the length of the new array.
When you want to add an element to the end of your array, use push().

array.push(element1, ..., elementN);
Enter fullscreen mode Exit fullscreen mode
const countries = ["Nigeria", "Ghana", "Rwanda"];

countries.push("Kenya");

console.log(countries); // ["Nigeria","Ghana","Rwanda","Kenya"]
Enter fullscreen mode Exit fullscreen mode

5.pop

The pop() method removes the last element from an array and returns that value to the caller. If you call pop() on an empty array, it returns undefined.

Array.prototype.shift() has similar behaviour to pop(), but applied to the first element in an array.

array.pop();
Enter fullscreen mode Exit fullscreen mode
const plants = ['broccoli', 'cauliflower', 'cabbage', 'kale', 'tomato'];

console.log(plants.pop());
// expected output: "tomato"

console.log(plants);
// expected output: Array ["broccoli", "cauliflower", "cabbage", "kale"]
Enter fullscreen mode Exit fullscreen mode

6.splice

The splice() method is a general-purpose method for changing the contents of an array by removing, replacing, or adding elements in specified positions of the array. This section will cover how to use this method to add an element to a specific location.

array.splice(index, howMany, [element1][, ..., elementN]);
Enter fullscreen mode Exit fullscreen mode
const fruits = ["Banana", "Orange", "Apple", "Mango"];

fruits.splice(2, 0, "Lemon", "Kiwi"); //Banana,Orange,Lemon,Kiwi,Apple,Mango
Enter fullscreen mode Exit fullscreen mode

7.slice

The slice() method returns a shallow copy of a portion of an array into a new array object selected from start to end (end not included) where start and end represent the index of items in that array. The original array will not be modified.

array.slice( begin [,end] );
Enter fullscreen mode Exit fullscreen mode
const animals = ['ant', 'bison', 'camel', 'duck', 'elephant'];

console.log(animals.slice(2));
// expected output: Array ["camel", "duck", "elephant"]

console.log(animals.slice(2, 4));
// expected output: Array ["camel", "duck"]
Enter fullscreen mode Exit fullscreen mode

8.shift

shift() is a built-in JavaScript function that removes the first element from an array. The shift() function directly modifies the JavaScript array with which you are working. shift() returns the item you have removed from the array.

The shift() function removes the item at index position 0 and shifts the values at future index numbers down by one.

array.shift();
Enter fullscreen mode Exit fullscreen mode
const array1 = [1, 2, 3];

const firstElement = array1.shift();

console.log(array1);
// expected output: Array [2, 3]

console.log(firstElement);
// expected output: 1
Enter fullscreen mode Exit fullscreen mode

9.unshift

The unshift() method inserts the given values to the beginning of an array-like object.

Array.prototype.push() has similar behaviour to unshift(), but applied to the end of an array.

array.unshift( element1, ..., elementN );
Enter fullscreen mode Exit fullscreen mode
const array1 = [1, 2, 3];

console.log(array1.unshift(4, 5));
// expected output: 5

console.log(array1);
// expected output: Array [4, 5, 1, 2, 3]
Enter fullscreen mode Exit fullscreen mode

10.join

JavaScript array join() is a built-in method that creates and returns the new string by concatenating all of the elements of the array. The join() method joins the array’s items into the string and returns that string. The specified separator will separate the array of elements. The default separator is a comma (,).

array.join(separator);
Enter fullscreen mode Exit fullscreen mode
const elements = ['Fire', 'Air', 'Water'];

console.log(elements.join());
// expected output: "Fire,Air,Water"

console.log(elements.join(''));
// expected output: "FireAirWater"

console.log(elements.join('-'));
// expected output: "Fire-Air-Water"
Enter fullscreen mode Exit fullscreen mode

11.every

The every() method tests whether all elements in the array pass the test implemented by the provided function. It returns a Boolean value.

array.every(callback[, thisObject]);
Enter fullscreen mode Exit fullscreen mode
const isBelowThreshold = (currentValue) => currentValue < 40;

const array1 = [1, 30, 39, 29, 10, 13];

console.log(array1.every(isBelowThreshold));
// expected output: true
Enter fullscreen mode Exit fullscreen mode

12.filter

The filter() method creates a shallow copy of a portion of a given array, filtered down to just the elements from the given array that pass the test implemented by the provided function.

array.filter(callback[, thisObject]);
Enter fullscreen mode Exit fullscreen mode
const words = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present'];

const result = words.filter(word => word.length > 6);

console.log(result);
// expected output: Array ["exuberant", "destruction", "present"]
Enter fullscreen mode Exit fullscreen mode

13.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.

array.indexOf(searchElement[, fromIndex]);
Enter fullscreen mode Exit fullscreen mode
const beasts = ['ant', 'bison', 'camel', 'duck', 'bison'];

console.log(beasts.indexOf('bison'));
// expected output: 1

// start from index 2
console.log(beasts.indexOf('bison', 2));
// expected output: 4

console.log(beasts.indexOf('giraffe'));
// expected output: -1
Enter fullscreen mode Exit fullscreen mode

14.reduce

The reduce() method executes a user-supplied "reducer" callback function on each element of the array, in order, passing in the return value from the calculation on the preceding element. The final result of running the reducer across all elements of the array is a single value.

array.reduce(callback[, initialValue]);
Enter fullscreen mode Exit fullscreen mode
const array1 = [1, 2, 3, 4];

// 0 + 1 + 2 + 3 + 4
const initialValue = 0;
const sumWithInitial = array1.reduce(
  (previousValue, currentValue) => previousValue + currentValue,
  initialValue
);

console.log(sumWithInitial)
Enter fullscreen mode Exit fullscreen mode

15.reverse

The reverse() method reverses an array in place and returns the reference to the same array, the first array element now becoming the last, and the last array element becoming the first. In other words, elements order in the array will be turned towards the direction opposite to that previously stated.

array.reverse();
Enter fullscreen mode Exit fullscreen mode
const array1 = ['one', 'two', 'three'];
console.log('array1:', array1);
// expected output: "array1:" Array ["one", "two", "three"]

const reversed = array1.reverse();
console.log('reversed:', reversed);
// expected output: "reversed:" Array ["three", "two", "one"]

// Careful: reverse is destructive -- it changes the original array.
console.log('array1:', array1);
// expected output: "array1:" Array ["three", "two", "one"]
Enter fullscreen mode Exit fullscreen mode

16.sort

The sort() method sorts the elements of an array in place and returns the reference to the same array, now sorted. The default sort order is ascending, built upon converting the elements into strings, then comparing their sequences of UTF-16 code units values.

array.sort( compareFunction );
Enter fullscreen mode Exit fullscreen mode
const months = ['March', 'Jan', 'Feb', 'Dec'];
months.sort();
console.log(months);
// expected output: Array ["Dec", "Feb", "Jan", "March"]

const array1 = [1, 30, 4, 21, 100000];
array1.sort();
console.log(array1);
// expected output: Array [1, 100000, 21, 30, 4]
Enter fullscreen mode Exit fullscreen mode

17.toString

The toString() method returns a string representing the object.

array.toString();
Enter fullscreen mode Exit fullscreen mode
function Dog(name) {
  this.name = name;
}

const dog1 = new Dog('Gabby');

Dog.prototype.toString = function dogToString() {
  return `${this.name}`;
};

console.log(dog1.toString());
// expected output: "Gabby"
Enter fullscreen mode Exit fullscreen mode

18.at

The at() method takes an integer value and returns the item at that index, allowing for positive and negative integers. Negative integers count back from the last item in the array.

array.at(index)
Enter fullscreen mode Exit fullscreen mode
const array1 = [5, 12, 8, 130, 44];

let index = 2;

console.log(`Using an index of ${index} the item returned is ${array1.at(index)}`);
// expected output: "Using an index of 2 the item returned is 8"

index = -2;

console.log(`Using an index of ${index} item returned is ${array1.at(index)}`);
// expected output: "Using an index of -2 item returned is 130"
Enter fullscreen mode Exit fullscreen mode

19.find

The find() method returns the first element in the provided array that satisfies the provided testing function. If no values satisfy the testing function, undefined is returned.

array.find(function(currentValue, index, arr),thisValue)
Enter fullscreen mode Exit fullscreen mode
const array1 = [5, 12, 8, 130, 44];

const found = array1.find(element => element > 10);

console.log(found);
// expected output: 12
Enter fullscreen mode Exit fullscreen mode

20.some

The some() method tests whether at least one element in the array passes the test implemented by the provided function. It returns true if, in the array, it finds an element for which the provided function returns true; otherwise it returns false. It doesn't modify the array.

array.some(callback[, thisObject]);
Enter fullscreen mode Exit fullscreen mode
const array = [1, 2, 3, 4, 5];

// checks whether an element is even
const even = (element) => element % 2 === 0;

console.log(array.some(even));
// expected output: true
Enter fullscreen mode Exit fullscreen mode

Top comments (25)

Collapse
 
yourmdsarfaraj profile image
MD Sarfaraj

Nice article, thanks for sharing!!

Collapse
 
codewithtee profile image
Tabassum Khanum

Welcome I am glad you took the time to read it.

Collapse
 
clay profile image
Clay Ferguson

I was unaware of a couple of those. Thanks for posting!

Collapse
 
codewithtee profile image
Tabassum Khanum

I'm glad that you are finding them useful.

Collapse
 
Sloan, the sloth mascot
Comment deleted
Collapse
 
codewithtee profile image
Tabassum Khanum

Hey Dennis! I used the markdown syntax highlighting and hope the snippets are more readable now.

Collapse
 
lionelrowe profile image
lionel-rowe

You need to specify the language β€” ruby is a different language, which is why the highlighting looks wierd β€” you want js.

```js
const x = js.syntaxHighlight() // comment
```
Enter fullscreen mode Exit fullscreen mode
const x = js.syntaxHighlight() // comment
Enter fullscreen mode Exit fullscreen mode
Thread Thread
 
codewithtee profile image
Tabassum Khanum

Thank you so for much lionel for correcting!

Collapse
 
miguelbarcelo profile image
MiguelBarcelo

Excellent job, well done!

Collapse
 
raguram90 profile image
RamR

the at method is new to me, thanks for this article.

Collapse
 
sainf profile image
Carlos Nogueira

beware at as 88% global usage caniuse and node -> 16.6, mdm

But it's nice to know !

Collapse
 
bsantosh909 profile image
Santosh Bhandari

Great read.

The only thing that I feel a bit off is the mention of .prototype usage.
It's not good to modify anything doing so.

Collapse
 
zeeshanahmadkhalil profile image
Zeeshan Ahmad Khalil

Lol I didn't knew shift removes the element I thought it adds in end and unshift adds at start since I use unshift mostly.

Thanks for sharing.

Collapse
 
andrewbaisden profile image
Andrew Baisden

Excellent article so many Array Methods.

Collapse
 
mikec711g profile image
Michael Casile

Nice article w/great examples.

Collapse
 
ifkas profile image
Ivo Culic

Check this guide for better visualizing the array methods: js-arrays-visualized.com/

Collapse
 
codewithtee profile image
Tabassum Khanum

This is really amazing! Thank you for sharing.