
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 Middle Element of an Array Using Recursion in JavaScript
We are required to write an array function, say findMiddle 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.
So, let’s write the code for this function. As you’ve already guessed, we will be making use of recursion to find these elements. The code for the recursive function will be −
Example
const arr = [1, 2, 3, 4, 5, 6, 7]; const array = [1, 2, 3, 4, 5, 6, 7, 8]; const findMiddle = (arr, ind = 0) => { if(arr[ind]){ return findMiddle(arr, ++ind); }; return ind % 2 !== 0 ? [arr[(ind-1) / 2]] : [arr[(ind/2)-1], arr[ind/2]]; }; console.log(findMiddle(arr)); console.log(findMiddle(array));
Output
The output in the console will be −
[ 4 ] [ 4, 5 ]
Advertisements