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.

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)])

Leave a Reply