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 find the middle element in an array.  However, there is always a solution for such a problem, only the approach differs.

I am going to demonstrate a simple solution for this problem that is beginner-friendly and easy to understand. To get the count of items in an array, we can make use of the length property.  We just need to do basic subtraction and division on that count to accomplish our goal.

In the following example, we have an array with an odd length. Upon click of a button, we will find the middle element in the array and display that on the screen. Please have a look over the code example and the steps given below.

HTML & CSS

  • We have 3 elements in the HTML file (div, button, and h1). The div element is just a wrapper for the rest of the elements.
  • The button element has “Get” and the h1 element has “Result” as innerText.
  • We have done some basic styling using CSS and added the link to our style.css stylesheet inside the head element.
  • We have also included our javascript file script.js with a script tag at the bottom.
<!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>
body {
    text-align: center;
}

div {
    display: inline-block;
}

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

Javascript

  • We have selected the button element and the h1 element using the document.querySelector() method and stored them in btnGet and result variables respectively.
  • We have global variable users which holds an array of strings.
  • We have attached a click event listener to the button element.
  • In the event handler function, we are subtracting 1 from the length of the array and dividing it by 2. After this calculation, the result will be 2 and we are storing that in the output variable
  • The output is the index of the middle element and we are displaying that element in the h1 element using the innerText property.

NOTE:   In this tutorial, the length of the array is an odd number.  In case the length is an even number, I recommend you to wrap the output with Math.floor() function.

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];
});