- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- 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 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 ]
- Related Articles
- How to insert an element into all positions in an array using recursion - JavaScript?
- Finding product of an array using recursion in JavaScript
- How to select the middle of an array? - JavaScript
- JavaScript: How to Find the Middle Element of a Linked List?
- Using recursion to remove consecutive duplicate entries from an array - JavaScript
- Adding an element in an array using Javascript
- Using recursion to remove consecutive duplicate entries from an array in JavaScript
- Array flattening using loops and recursion in JavaScript
- Modified version of summing an array with recursion in JavaScript
- How to find middle element in a array in android?
- How to find the min/max element of an Array in JavaScript?
- Finding the majority element of an array JavaScript
- Find the only different element in an array using C++
- Place an element in the middle of the parent element in Bootstrap 4
- How to find the maximum element of an Array using STL in C++?

Advertisements