
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
Find the Center of an Array without ES6 Functions in JavaScript
We are required to write an array function midElement() that returns the middlemost element of the array without accessing its length property and without using any kind of built-in loops.
If the array contains an odd number of elements, we return the one, middlemost element, or if the array contains an even number of elements, we return an array of two middlemost elements.
Example
Following is the code −
const arr = [14, 32, 36, 42, 45, 66, 87]; const array = [13, 92, 83, 74, 55, 46, 74, 82]; const midElement = (arr, ind = 0) => { if(arr[ind]){ return midElement(arr, ++ind); }; return ind % 2 !== 0 ? [arr[(ind-1) / 2]] : [arr[(ind/2)-1], arr[ind/2]]; }; console.log(midElement(arr)); console.log(midElement(array));
Output
This will produce the following output in console −
[ 42 ] [ 74, 55 ]
Advertisements