Javascript Home

Arrays

The Length Property

The length property of an array returns the length of an array (the number of array elements).


<p id="demo"></p>

<script>

  const fruits = ["Banana", "Orange", "Apple", "Mango"];

  document.getElementById("demo").innerHTML = fruits.length;

</script>

Accessing Array Elements

First Element

JavaScript array elements are accessed using numeric indexes (starting from 0).


<p id="demo1"></p>

<script>

  const fruits_1 = ["Banana", "Orange", "Apple", "Mango"];

  document.getElementById("demo1").innerHTML = fruits_1[0];

</script>

Last Element


<p id="demo2"></p>

<script>

  const fruits_2 = ["Banana", "Orange", "Apple", "Mango"];

  document.getElementById("demo2").innerHTML = fruits_2[fruits_2.length-1];

</script>

Looping Array Elements

for Loop

One way to loop through an array is using a for loop.


<p id="demo3"></p>

<script>

  const fruits_3 = ["Banana", "Orange", "Apple", "Mango"];

  let fLen = fruits_3.length;

  let text = "<ul>";

  for (let i = 0; i < fLen; i++) {

    text += "<li>" + fruits_3[i] + "</li>";

  }

  text += "</ul>";

  document.getElementById("demo3").innerHTML = text;

</script>

for Loop

You can also use the Array.forEach() function:


<p id="demo4"></p>

<script>

  const fruits_4 = ["Banana", "Orange", "Apple", "Mango"];

  let text1 = "<ul>";

  fruits_4.forEach(myFunction);

  text1 += "</ul>";

  document.getElementById("demo4").innerHTML = text1;

  function myFunction(value) {

    text1 += "<li>" + value + "</li>";

  }

</script>

Adding Array Elements

The easiest way to add a new element to an array is using the push() method.


<button type="button" class="btn btn-primary mb-5" onclick="myFunction1()">Try it</button>

<p id="demo5"></p>

<script>

  const fruits_5 = ["Banana", "Orange", "Apple"];

  document.getElementById("demo5").innerHTML = fruits_5;

  function myFunction1() {

    fruits_5.push("Lemon");

    document.getElementById("demo5").innerHTML = fruits_5;

  }

</script>


The length property provides an easy way to append new elements to an array without using the push() method.


<button type="button" class="btn btn-primary mb-5" onclick="myFunction2()">Try it</button>

<p id="demo6"></p>

<script>

  const fruits_6 = ["Banana", "Orange", "Apple"];

  document.getElementById("demo6").innerHTML = fruits_6;

  function myFunction2() {

    fruits_6[fruits_6.length] = "Lemon";

    document.getElementById("demo6").innerHTML = fruits_6;

  }

</script>

Converting Arrays To Strings

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


<p id="demo7"></p>

<script>

  const fruits_7 = ["Banana", "Orange", "Apple", "Mango"];

  document.getElementById("demo7").innerHTML = fruits_7.toString();

</script>


The join() method also joins all array elements into a string.

It behaves just like toString(), but in addition you can specify the separator.


<p id="demo8"></p>

<script>

  const fruits_8 = ["Banana", "Orange", "Apple", "Mango"];

  document.getElementById("demo8").innerHTML = fruits_8.join(" * ");

</script>

Popping And Pushing

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


<p id="demo9"></p>

<p id="demo10"></p>

<script>

  const fruits_9 = ["Banana", "Orange", "Apple", "Mango"];

  document.getElementById("demo9").innerHTML = fruits_9;

  fruits_9.pop();

  document.getElementById("demo10").innerHTML = fruits_9;

</script>


The pop() method returns the value that was "popped out".


<p id="demo11"></p>

<p id="demo12"></p>

<script>

  const fruits_10 = ["Banana", "Orange", "Apple", "Mango"];

  document.getElementById("demo11").innerHTML = fruits_10.pop();

  document.getElementById("demo12").innerHTML = fruits_10;

</script>


The push() method appends a new element to an array.


<p id="demo13"></p>

<p id="demo14"></p>

<script>

  const fruits_11 = ["Banana", "Orange", "Apple", "Mango"];

  document.getElementById("demo13").innerHTML = fruits_11;

  fruits_11.push("Kiwi");

  document.getElementById("demo14").innerHTML = fruits_11;

</script>


The push() method returns the new array length.


<p id="demo15"></p>

<p id="demo16"></p>

<script>

  const fruits_12 = ["Banana", "Orange", "Apple", "Mango"];

  document.getElementById("demo15").innerHTML = fruits_12.push("Kiwi");

  document.getElementById("demo16").innerHTML = fruits_12;

</script>

Shifting Elements

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


<p id="demo17"></p>

<p id="demo18"></p>

<script>

  const fruits_13 = ["Banana", "Orange", "Apple", "Mango"];

  document.getElementById("demo17").innerHTML = fruits_13;

  fruits_13.shift();

  document.getElementById("demo18").innerHTML = fruits_13;

</script>


The shift() method returns the value that was "shifted out".


<p id="demo19"></p>

<p id="demo20"></p>

<script>

  const fruits_14 = ["Banana", "Orange", "Apple", "Mango"];

  document.getElementById("demo19").innerHTML = fruits_14.shift();

  document.getElementById("demo20").innerHTML = fruits_14;

</script>


The unshift() method adds new elements to the beginning of an array.


<p id="demo21"></p>

<p id="demo22"></p>

<script>

  const fruits_15 = ["Banana", "Orange", "Apple", "Mango"];

  document.getElementById("demo21").innerHTML = fruits_15;

  fruits_15.unshift("Lemon");

  document.getElementById("demo22").innerHTML = fruits_15;

</script>


The unshift() method returns the length of the new array.


<p id="demo23"></p>

<p id="demo24"></p>

<script>

  const fruits_16 = ["Banana", "Orange", "Apple", "Mango"];

  document.getElementById("demo23").innerHTML = fruits_16.unshift("Lemon");

  document.getElementById("demo24").innerHTML = fruits_16;

</script>


Array elements are accessed using their index number.


<p id="demo25"></p>

<p id="demo26"></p>

<script>

  const fruits_17 = ["Banana", "Orange", "Apple", "Mango"];

  document.getElementById("demo25").innerHTML = fruits_17;

  fruits_17[0] = "Kiwi";

  document.getElementById("demo26").innerHTML = fruits_17;

</script>


Array elements can be deleted using the JavaScript operator delete.


<p id="demo27"></p>

<p id="demo28"></p>

<script>

  const fruits_18 = ["Banana", "Orange", "Apple", "Mango"];

  document.getElementById("demo27").innerHTML = "The first fruit is: " + fruits_18[0];

  delete fruits_18[0];

  document.getElementById("demo28").innerHTML = fruits_18[0];

</script>

Merging (Concatenating) Arrays

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


<p id="demo29"></p>

<script>

  const myGirls = ["Cecilie", "Lone"];

  const myBoys = ["Emil", "Tobias", "Linus"];

  const myChildren = myGirls.concat(myBoys);

  document.getElementById("demo29").innerHTML = myChildren;

</script>


The concat() method can take any number of array arguments.


<p id="demo30"></p>

<script>

  const array1 = ["Cecilie", "Lone"];

  const array2 = ["Emil", "Tobias", "Linus"];

  const array3 = ["Robin", "Morgan"];

  const myChildren_1 = array1.concat(array2, array3);

  document.getElementById("demo30").innerHTML = myChildren_1;

</script>


The concat() method can also take strings as arguments.


<p id="demo31"></p>

<script>

  const myArray = ["Emil", "Tobias", "Linus"];

  const myChildren_2 = myArray.concat("Peter");

  document.getElementById("demo31").innerHTML = myChildren_2;

</script>

Splicing And Slicing Arrays

The splice() method adds and/or removes array elements.

The splice() method overwrites the original array.

Array.splice( index, remove_count, item_list )

index                     Required. The position to add/remove items. Negative value defines the position from the end of the array.

remove_count       The number of elements to be removed from the starting index.

items_list               The list of new items separated by a comma operator that is to be inserted from the starting index.



<p id="demo32"></p>

<p id="demo33"></p>

<script>

  const fruits_19 = ["Banana", "Orange", "Apple", "Mango"];

  document.getElementById("demo32").innerHTML = fruits_19;

  fruits_19.splice(2, 0, "Lemon", "Kiwi");

  document.getElementById("demo33").innerHTML = fruits_19;

</script>


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").


<p id="demo38"></p>

<script>

  const fruits_22 = ["Banana", "Orange", "Lemon", "Apple", "Mango"];

  const citrus = fruits_22.slice(1);

  document.getElementById("demo38").innerHTML = fruits_22 + "<br><br>" + citrus;

</script>


This example slices out a part of an array starting from array element 3 ("Apple").


<p id="demo39"></p>

<script>

  const fruits_23 = ["Banana", "Orange", "Lemon", "Apple", "Mango"];

  const citrus_1 = fruits_23.slice(3);

  document.getElementById("demo39").innerHTML = fruits_23 + "<br><br>" + citrus_1;

</script>


The slice() method can take two arguments like slice(1, 3).

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


<p id="demo40"></p>

<script>

  const fruits_24 = ["Banana", "Orange", "Lemon", "Apple", "Mango"];

  const citrus_2 = fruits_24.slice(1,3);

  document.getElementById("demo40").innerHTML = fruits_24 + "<br><br>" + citrus_2;

</script>


If the end argument is omitted, like in the first examples, the slice() method slices out the rest of the array.

This example slices out a part of an array starting from array element 2 ("Lemon").


<p id="demo41"></p>

<script>

  const fruits_25 = ["Banana", "Orange", "Lemon", "Apple", "Mango"];

  const citrus_3 = fruits_25.slice(2);

  document.getElementById("demo41").innerHTML = fruits_25 + "<br><br>" + citrus_3;

</script>

Sorting An Array

The sort() method sorts an array alphabetically.


<p id="demo42"></p>

<p id="demo43"></p>

<script>

  const fruits_26 = ["Banana", "Orange", "Apple", "Mango"];

  document.getElementById("demo42").innerHTML = fruits_26;

  fruits_26.sort();

  document.getElementById("demo43").innerHTML = fruits_26;

</script>


The reverse() method reverses the elements in an array.


<p id="demo44"></p>

<p id="demo45"></p>

<script>

  const fruits_27 = ["Banana", "Orange", "Apple", "Mango"];

  document.getElementById("demo44").innerHTML = fruits_27;

  fruits_27.sort();

  fruits_27.reverse();

  document.getElementById("demo45").innerHTML = fruits_27;

</script>


By default, the sort() function sorts values as strings.

Because of this, the sort() method will produce incorrect result when sorting numbers.

This can be fixed by providing a compare function.


<p id="demo46"></p>

<p id="demo47"></p>

<script>

  const points = [40, 100, 1, 5, 25, 10];

  document.getElementById("demo46").innerHTML = points;

  points.sort(function(a, b){return a - b});

  document.getElementById("demo47").innerHTML = points;

</script>


Use the same technique to sort an array descending.


<p id="demo48"></p>

<p id="demo49"></p>

<script>

  const points_1 = [40, 100, 1, 5, 25, 10];

  document.getElementById("demo48").innerHTML = points_1;

  points_1.sort(function(a, b){return b - a});

  document.getElementById("demo49").innerHTML = points_1;

</script>


Numerically And Alphabetically Sorting.


<p id="demo50"></p>

<button type="button" class="btn btn-primary mb-5" onclick="myFunction3()">Sort Alphabetically</button>

<button type="button" class="btn btn-primary mb-5" onclick="myFunction4()">Sort Numerically</button>

<script>

  const points_2 = [40, 100, 1, 5, 25, 10];

  document.getElementById("demo50").innerHTML = points_2;

  function myFunction3() {

    points_2.sort();

    document.getElementById("demo50").innerHTML = points_2;

  }

  function myFunction4() {

    points_2.sort(function(a, b){return a - b});

    document.getElementById("demo50").innerHTML = points_2;

  }

</script>


Sorting An Array In Random Order.


<p id="demo51"></p>

<button type="button" class="btn btn-primary mb-5" onclick="myFunction5()">Sort</button>

<script>

  const points_3 = [40, 100, 1, 5, 25, 10];

  document.getElementById("demo51").innerHTML = points_3;

  function myFunction5() {

    points_3.sort(function(a, b){return 0.5 - Math.random()});

    document.getElementById("demo51").innerHTML = points_3;

  }

</script>


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

The highest number is .


<p> The highest number is <span id="demo52"></span>.</p>

<script>

  const points_4 = [40, 100, 1, 5, 25, 10];

  document.getElementById("demo52").innerHTML = myArrayMax(points_4);

  function myArrayMax(arr) {

    return Math.max(...arr);

  }

</script>


You can use Math.min to find the lowest number in an array.

The lowest number is .


<p> The lowest number is <span id="demo53"></span>.</p>

<script>

  const points_5 = [40, 100, 1, 5, 25, 10];

  document.getElementById("demo53").innerHTML = myArrayMin(points_5);

  function myArrayMin(arr_1) {

    return Math.min(...arr_1);

  }

</script>

Sorting Object Arrays

JavaScript arrays often contain objects.

Sort car objects on age:


<p id="demo54"></p>

<script>

  const cars = [

    {type:"Volvo", year:2016},

    {type:"Saab", year:2001},

    {type:"BMW", year:2010}

  ];

  cars.sort(function(a, b){return a.year - b.year});

  displayCars();

  function displayCars() {

    document.getElementById("demo54").innerHTML =

    cars[0].type + " " + cars[0].year + "<br>" +

    cars[1].type + " " + cars[1].year + "<br>" +

    cars[2].type + " " + cars[2].year;

  }

</script>


Comparing string properties is a little more complex.

Click the buttons to sort car objects on type.


<button type="button" class="btn btn-primary mb-5" onclick="myFunction14()">Sort</button>

<p id="demo55"></p>

<script>

  const cars_1 = [

    {type:"Volvo", year:2016},

    {type:"Saab", year:2001},

    {type:"BMW", year:2010}

  ];

  displayCars();

  function myFunction14() {

    cars_1.sort(function(a, b){

      let x = a.type.toLowerCase();

      let y = b.type.toLowerCase();

      if (x < y) {return -1;}

      if (x > y) {return 1;}

      return 0;

    });

    displayCars();

  }

  function displayCars() {

    document.getElementById("demo55").innerHTML =

    cars_1[0].type + " " + cars_1[0].year + "<br>" +

    cars_1[1].type + " " + cars_1[1].year + "<br>" +

    cars_1[2].type + " " + cars_1[2].year;

  }

</script>

Array Iteration

The forEach() method calls a function (a callback function) once for each array element.


<p id="demo56"></p>

<script>

  const numbers = [45, 4, 9, 16, 25];

  let txt = "";

  numbers.forEach(myFunction6);

  document.getElementById("demo56").innerHTML = txt;

  function myFunction6(value, index, array) {

    txt += value + "<br>";

  }

</script>


The map() method creates a new array by performing a function on each array element.


<p id="demo57"></p>

<script>

  const numbers1 = [45, 4, 9, 16, 25];

  const numbers2 = numbers1.map(myFunction7);

  document.getElementById("demo57").innerHTML = numbers2;

  function myFunction7(value, index, array) {

    return value * 2;

  }

</script>


The filter() method creates a new array with array elements that passes a test.


<p id="demo58"></p>

<script>

  const numbers3 = [45, 4, 9, 16, 25];

  const numbers4 = numbers3.filter(myFunction8);

  document.getElementById("demo58").innerHTML = numbers4;

  function myFunction8(value, index, array) {

    return value > 18;

  }

</script>


The reduce() method runs a function on each array element to produce (reduce it to) a single value.


<p id="demo59"></p>

<script>

  const numbers5 = [45, 4, 9, 16, 25];

  const sum = numbers5.reduce(myFunction9);

  document.getElementById("demo59").innerHTML = "The sum is " + sum;

  function myFunction9(total, value, index, array) {

    return total + value;

  }

</script>


The every() method checks if all array values pass a test.


<p id="demo60"></p>

<script>

  const numbers6 = [45, 4, 9, 16, 25];

  const checkResult = numbers6.every(myFunction10);

  document.getElementById("demo60").innerHTML = "All over 18 is " + checkResult;

  function myFunction10(value, index, array) {

    return value > 18;

  }

</script>


The some() method checks if some array values pass a test.


<p id="demo61"></p>

<script>

  const numbers7 = [45, 4, 9, 16, 25];

  const checkResult1 = numbers7.some(myFunction11);

  document.getElementById("demo61").innerHTML = "Some over 18 is " + checkResult1;

  function myFunction11(value, index, array) {

    return value > 18;

  }

</script>


The indexOf() searches an array for an element value and returns its position.


<p id="demo62"></p>

<script>

  const fruits_20 = ["Apple", "Orange", "Apple", "Mango"];

  let position = fruits_20.indexOf("Apple") + 1;

  document.getElementById("demo62").innerHTML = "Apple is found in position " + position;

</script>


The lastIndexOf() returns the position of the last occurrence of the specified element.


<p id="demo63"></p>

<script>

  const fruits_21 = ["Apple", "Orange", "Apple", "Mango"];

  let position1 = fruits_21.lastIndexOf("Apple") + 1;

  document.getElementById("demo63").innerHTML = "Apple is found in position " + position1;

</script>


The find() method returns the value of the first array element that passes a test function.


<p id="demo64"></p>

<script>

  const numbers8 = [4, 9, 16, 25, 29];

  let first = numbers8.find(myFunction12);

  document.getElementById("demo64").innerHTML = "First number over 18 is " + first;

  function myFunction12(value, index, array) {

    return value > 18;

  }

</script>


The findIndex() method returns the index of the first array element that passes a test function.


  <p id="demo65"></p>

  <script>

    const numbers9 = [4, 9, 16, 25, 29];

    document.getElementById("demo65").innerHTML = "First number over 18 has index " + numbers9.findIndex(myFunction13);

    function myFunction13(value, index, array) {

      return value > 18;

    }

  </script>


The Array.keys() method returns an Array Iterator object with the keys of an array.


  <p id="demo66"></p>

  <script>

    const fruits_28 = ["Banana", "Orange", "Apple", "Mango"];

    const keys = fruits_28.keys();

    let text2 = "";

    for (let x of keys) {

      text2 += x + "<br>";

    }

    document.getElementById("demo66").innerHTML = text2;

  </script>


The entries() method returns an Array Iterator object with the key/value pairs.


  <p id="demo67"></p>

  <script>

    const fruits_29 = ["Banana", "Orange", "Apple", "Mango"];

    const f = fruits_29.entries();

    for (let x of f) {

      document.getElementById("demo67").innerHTML += x + "<br>";

    }

  </script>


The Array.includes() allows a check for NaN values, unlike Array.indexOf().


  <p id="demo68"></p>

  <script>

    const fruits_30 = ["Banana", "Orange", "Apple", "Mango"];

    document.getElementById("demo68").innerHTML = fruits_30.includes("Mango");

  </script>