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.
Therefore, let’s write the code for this function −
Example
The code for this will be −
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
The output in the console will be −
[ 42 ] [ 74, 55 ]