How to Find Middle Element in Array in Javascript

In this tutorial, you will learn how to find middle element in array in javascript. We do not have any built-in methods in javascript to get middle element of an array.  However, there are always solutions for such problem and those solutions are countless.

We are going to cover very basic approach in this tutorial to find middle element in an array. The approach is beginner friendly and easy to understand. Please have a look over example code and steps given below.

  • We have 2 elements in the HTML file (button and h1)
  • We have done some basic styling using CSS.
  • We are getting reference of those elements using querySelector() method in the javascript file and storing them in btnGet and result variable.
  • We have created users variable which holds array of strings as value.
  • We have added click() event listener to the button element, so that we can get middle element of the array and display it on the screen.
  • As you already know, indexes in array are 0 based. To find the middle element, first we need to get length of the array using length property and subtract 1 from it.  Then, we need to divide it by 2 to get the middle element.  In our case, length of array is an odd number.  In case the length is even number, I recommend you to wrap the output with Math.floor() function.
  • We are storing the result of above calculation in output variable.
  • Now that we have got our output which is the index of middle element in the array, we can display its value inside h1 element.

HTML:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <link rel="stylesheet" href="style.css">
    <title>Document</title>
</head>
<body>
    
    <div>
        <button>Get</button>
        <h1>Result</h1>
    </div>
    
    <script src="script.js"></script>
</body>
</html>

 

CSS:

body {
    text-align: center;
}

div {
    display: inline-block;
}

button {
    display: inline-block;
    padding: 10px 20px;
}

 

Javascript:

let btnGet = document.querySelector('button');

let result = document.querySelector('h1');

let users = ['James', 'Marks', 'John', 'Mary', 'Ronald'];

btnGet.addEventListener('click', () => {
    let output = (users.length - 1) / 2;

    result.innerText = users[output];
});

 

  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •