Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to extract the middle item or (Two Items in Middle) from an array regardless of Odd or Even Number of Items?

When I extract middle item from odd number of elements:


var givenArray = ['Maths','English', 'Social', 'Economics','Tech']
console.log(givenArray[((givenArray.length-1)/2)])

It provides output to be social which is what I am expecting but in case the number of items is even :

var givenArray = ['Maths','English', 'Social', 'Economics']
console.log(givenArray[((givenArray.length)/2)])

I get output Social.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

The actual question here is, How can I access the middle item (2 middle items if it’s odd) without worrying to get Undefined as output regardless of the number of items being odd or even.

I could do that by using conditional statements but I don’t want to do so. is there any other way?

P.S: I’m a beginner.

>Solution :

You can try to do that with roundof. No need to check for even or odd.

var givenArray=['Maths','English', 'Social', 'Economics'];
console.log(givenArray[Math.round((givenArray.length-1)/2)])
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading