 
  Data Structure Data Structure
 Networking Networking
 RDBMS RDBMS
 Operating System Operating System
 Java Java
 MS Excel MS Excel
 iOS iOS
 HTML HTML
 CSS CSS
 Android Android
 Python Python
 C Programming C Programming
 C++ C++
 C# C#
 MongoDB MongoDB
 MySQL MySQL
 Javascript Javascript
 PHP PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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 ]
Advertisements
 