How to select the middle of an array?  - JavaScript


We are required to write a JavaScript function that takes in an array of Numbers.

The function should return the middlemost element of the array.

For example −

If the array is −

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

Then the output should be 4

Example

Following is the code −

const arr = [1, 2, 3, 4, 5, 6, 7];
const middle = function(){
   const half = this.length >> 1;
   const offset = 1 - this.length % 2;
   return this.slice(half - offset, half + 1);
};
Array.prototype.middle = middle;
console.log(arr.middle());
console.log([1, 2, 3, 4, 5, 6].middle());

Output

This will produce the following output on console −

[ 4 ]
[ 3, 4 ]

Updated on: 01-Oct-2020

445 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements