
- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
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 ]
- Related Questions & Answers
- Checking an array for palindromes - JavaScript
- Find the middle element of an array using recursion JavaScript
- Recursive multiplication in array - JavaScript
- Insert value in the middle of every value inside array JavaScript
- JavaScript: How to Find the Middle Element of a Linked List?
- Middle of three elements - JavaScript
- Select results from the middle of a sorted list in MySQL?
- The globals(), locals() and reload() Functions in Python
- The time Module in Python
- The calendar Module in Python
- The Anonymous Functions in Python
- The return Statement in Python
- The import Statements in Python
- The Threading Module in Python
- The match Function in Python
Advertisements