
- 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
Finding middlemost element(s) in 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
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 ]
- Related Articles
- Finding middlemost node of a linked list in JavaScript
- Finding distance to next greater element in JavaScript
- Finding first unique element in sorted array in JavaScript
- Finding shared element between two strings - JavaScript
- Finding the first redundant element in an array - JavaScript
- Finding element greater than its adjacent elements in JavaScript
- Finding missing element in an array of numbers in JavaScript
- Finding the majority element of an array JavaScript
- Finding sum of every nth element of array in JavaScript
- Finding the first unique element in a sorted array in JavaScript
- Finding the most frequent word(s) in an array using JavaScript
- Finding nth element of an increasing sequence using JavaScript
- Finding nth element of the Padovan sequence using JavaScript
- Finding the nth element of the lucas number sequence in JavaScript
- Finding smallest element in a sorted array which is rotated in JavaScript

Advertisements