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 ]

Updated on: 25-Aug-2020

298 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements