Javascript arrays methods

, 24/09/2017

Converting Arrays to Strings

The JavaScript method toString() converts an array to a string of (comma separated) array values.

var fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo").innerHTML = fruits.toString();
// result : Banana,Orange,Apple,Mango

The join() method also joins all array elements into a string. It behaves just like toString(), but in addition you can specify the separator:

var fruits = ["Banana", "Orange","Apple", "Mango"];
document.getElementById("demo").innerHTML = fruits.join(" * ");
// result : Banana * Orange * Apple * Mango


The pop() method removes the last element from an array:

var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.pop();              // Removes the last element ("Mango") from fruits

The pop() method returns the value that was « popped out »:

 var fruits = ["Banana", "Orange", "Apple", "Mango"];
var x = fruits.pop();      // the value of x is "Mango" 


The push() method adds a new element to an array (at the end):

var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.push("Kiwi");       //  Adds a new element ("Kiwi") to fruits

The push() method returns the new array length:

var fruits = ["Banana", "Orange", "Apple", "Mango"];
var x = fruits.push("Kiwi");   //  the value of x is 5 


The shift() method removes the first array element and « shifts » all other elements to a lower index.

var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.shift();            // Removes the first element "Banana" from fruits 

Splicing an Array

The splice() method can be used to add new items to an array:

ar fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.splice(2, 0, "Lemon", "Kiwi");

The first parameter (2) defines the position where new elements should be added (spliced in).
The second parameter (0) defines how many elements should be removed.
The rest of the parameters (« Lemon » , « Kiwi ») define the new elements to be added.

Using splice() to Remove Elements

var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.splice(0, 1);        // Removes the first element of fruits 

Merging (Concatenating) Arrays

The concat() method creates a new array by merging (concatenating) existing arrays:

 var myGirls = ["Cecilie", "Lone"];
var myBoys = ["Emil", "Tobias","Linus"];
var myChildren = myGirls.concat(myBoys);     // Concatenates (joins) myGirls and myBoys 

Slicing an Array

The slice() method slices out a piece of an array into a new array.
This example slices out a part of an array starting from array element 1 (« Orange »):

var fruits = ["Banana", "Orange", "Lemon", "Apple", "Mango"];
var citrus = fruits.slice(1);
var fruits = ["Banana", "Orange", "Lemon", "Apple", "Mango"];
var citrus = fruits.slice(1, 3);

The method then selects elements from the start argument, and up to (but not including) the end argument.

Note also than the slice() method creates a new array. It does not remove any elements from the source array.

Sorting and reverse an Array

The sort() method sorts an array alphabetically:

var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.sort();            // Sorts the elements of fruits
fruits.reverse();         // Reverses the order of the elements 

Numeric Sort

By default, the sort() function sorts values as strings. This works well for strings (« Apple » comes before « Banana »).

However, if numbers are sorted as strings, « 25 » is bigger than « 100 », because « 2 » is bigger than « 1 ». Because of this, the sort() method will produce incorrect result when sorting numbers.

You can fix this by providing a compare function:

var points = [40, 100, 1, 5, 25, 10];
points.sort(function(a, b){return a - b});

Use the same trick to sort an array descending:

var points = [40, 100, 1, 5, 25, 10];
points.sort(function(a, b){return b - a});

Sorting an Array in Random Order

var points = [40, 100, 1, 5, 25, 10];
points.sort(function(a, b){return 0.5 - Math.random()});

Find the Highest (or Lowest) Array Value

Sorting ascending

var points = [40, 100, 1, 5, 25, 10];
points.sort(function(a, b){return a - b});
// now points[0] contains the lowest value
// and points[points.length-1] contains the highest value

Sorting descending

var points = [40, 100, 1, 5, 25, 10];
points.sort(function(a, b){return b - a});
// now points[0] contains the highest value
// and points[points.length-1] contains the lowest value 

You can use Math.max.apply to find the highest number in an array:

function myArrayMax(arr) {
    return Math.max.apply(null, arr);

And to find the lowest

function myArrayMin(arr) {
    return Math.min.apply(null, arr);

Another Useful methods


Use case : Check for any occurence of « orange » in an array.

var arr = ['apple','orange','pear'];

console.log("found:", arr.indexOf("orange") != -1);


Use case : Find all the items in the array that have the name « orange »

var arr = [
    {"name":"apple", "count": 2},
    {"name":"orange", "count": 5},
    {"name":"pear", "count": 3},
    {"name":"orange", "count": 16},
var newArr = arr.filter(function(item){
    return === "orange";


Use case : Iterate through an array

var arr = [1,2,3,4,5,6,7,8];

// Uses the usual "for" loop to iterate
for(var i= 0, l = arr.length; i< l; i++){


//Uses forEach to iterate


Use case : Parse and return a array of objects that contains a additional new property, full_name

var oldArr = [{first_name:"Colin",last_name:"Toh"},{first_name:"Addy",last_name:"Osmani"},{first_name:"Yehuda",last_name:"Katz"}];

function getNewArr(){
        item.full_name = [item.first_name,item.last_name].join(" ");
        return item;



Use case : Parse the array and return an object that contains the number of times each string occured in the array

var arr = ["apple","orange","apple","orange","pear","orange"];

function getWordCnt(){
    return arr.reduce(function(prev,next){
        prev[next] = (prev[next] + 1) || 1;
        return prev;


Content taken from