
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
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
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 ]
Advertisements