Code to find the center of an array without using ES6 functions - 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 ]

Updated on: 18-Sep-2020

249 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements