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
The code for this will be −
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
The output in the console will be −
[ 4 ] [ 3, 4 ]