Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to select the middle of an array? - JavaScript
We are required to write a JavaScript function that takes in an array of numbers and returns the middlemost element(s) of the array.
For arrays with odd length, there's one middle element. For arrays with even length, there are two middle elements.
For example, if the array is:
const arr = [1, 2, 3, 4, 5, 6, 7];
Then the output should be [4] (the middle element at index 3).
Using Array Prototype Method
We can extend the Array prototype to add a middle() method that returns the middle element(s):
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());
[ 4 ] [ 3, 4 ]
Using a Simple Function
A cleaner approach is to create a standalone function:
function getMiddleElements(arr) {
const length = arr.length;
const middle = Math.floor(length / 2);
if (length % 2 === 1) {
// Odd length - return single middle element
return [arr[middle]];
} else {
// Even length - return two middle elements
return [arr[middle - 1], arr[middle]];
}
}
console.log(getMiddleElements([1, 2, 3, 4, 5])); // Odd
console.log(getMiddleElements([1, 2, 3, 4, 5, 6])); // Even
console.log(getMiddleElements([10])); // Single element
[ 3 ] [ 3, 4 ] [ 10 ]
How It Works
The bit shift operator >> 1 is equivalent to Math.floor(length / 2). For the offset calculation:
- If length is odd:
length % 2 = 1, sooffset = 1 - 1 = 0 - If length is even:
length % 2 = 0, sooffset = 1 - 0 = 1
This ensures we get one element for odd arrays and two elements for even arrays.
Conclusion
Use Math.floor(length / 2) to find the middle index. For even-length arrays, return both middle elements to handle the case where there's no single center element.
