
- Javascript Basics Tutorial
- Javascript - Home
- Javascript - Overview
- Javascript - Syntax
- Javascript - Enabling
- Javascript - Placement
- Javascript - Variables
- Javascript - Operators
- Javascript - If...Else
- Javascript - Switch Case
- Javascript - While Loop
- Javascript - For Loop
- Javascript - For...in
- Javascript - Loop Control
- Javascript - Functions
- Javascript - Events
- Javascript - Cookies
- Javascript - Page Redirect
- Javascript - Dialog Boxes
- Javascript - Void Keyword
- Javascript - Page Printing
- JavaScript Objects
- Javascript - Objects
- Javascript - Number
- Javascript - Boolean
- Javascript - Strings
- Javascript - Arrays
- Javascript - Date
- Javascript - Math
- Javascript - RegExp
- Javascript - HTML DOM
- JavaScript Advanced
- Javascript - Error Handling
- Javascript - Validations
- Javascript - Animation
- Javascript - Multimedia
- Javascript - Debugging
- Javascript - Image Map
- Javascript - Browsers
- JavaScript Useful Resources
- Javascript - Questions And Answers
- Javascript - Quick Guide
- Javascript - Functions
- Javascript - Resources
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 Articles
- Find the middle element of an array using recursion JavaScript
- Find the Middle Element of an array in JAVA
- Select random values from an array in JavaScript?
- Insert value in the middle of every value inside array JavaScript
- JavaScript: How to Find the Middle Element of a Linked List?
- How to find the length of an array in JavaScript?
- How to duplicate elements of an array in the same array with JavaScript?
- How to find the maximum value of an array in JavaScript?
- How to find the minimum value of an array in JavaScript?
- Select results from the middle of a sorted list in MySQL?
- How to create an array of integers in JavaScript?
- How to create an array of strings in JavaScript?
- How to sort an array of integers correctly JavaScript?
- How to add new array elements at the beginning of an array in JavaScript?
- How to convert Object’s array to an array using JavaScript?

Advertisements