

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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
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 ]
- Related Questions & Answers
- Flattening an array with truthy/ falsy values without using library functions - JavaScript
- C++ code to find center of inner box
- JavaScript: How to Find Min/Max Values Without Math Functions?
- JavaScript code to print last element of an array
- Find the middle element of an array using recursion JavaScript
- Finding square root of a number without using library functions - JavaScript
- How to find the missing number and the repeated number in a sorted array without using any inbuilt functions using C#?
- Find maximum in an array without using Relational Operators in C++
- Find minimum in an array without using Relational Operators in C++
- Find the difference of largest and the smallest number in an array without sorting it in JavaScript
- Reverse digits of an integer in JavaScript without using array or string methods
- How to find the length of an array in JavaScript?
- What are the different ways to find missing numbers in a sorted array without any inbuilt functions using C#?
- Find the center of the circle using endpoints of diameter in C++
- ES6 Property Shorthands in JavaScript
Advertisements