Simple Array question
how to print first, middle and last items of this array with a clean code?
11 Replies
does the homework assignment state whether it's always an odd number of elements?
No it just asks to print first, middle and last items
do you know how to access an item in an array?
Getting the first item should be super easy. The last and middle items both depend on obtaining the length of the array and doing some simple math. The only possible complication is figuring out which "middle" to output if you have an even number of array items, since there would actually be two middles.
Also note that there is a new at() array method that could make getting the last item super easy without knowing the length of the array, but this is new enough that your teacher might not even know it. If it wasn't covered in class, don't use it.
yeah the struggle here was about getting the middle item, we can access last item by (itCompanies.length -1)
I came with an idea to get middle item, which is ( (itCompanies.length -1) / 2 )
That's a perfectly valid solution, but there's a slightly more generic one that also works for even arrays (though it'll get the one right of the middle)
if you use
Math.floor(itCompanies.length / 2)
, you'll get 3 for an array of seven, which would give you "Apple"
even if you cut Amazon, you'd still get Apple, which is as valid as a middle as "Microsoft" would beThis specific formula only works if the length of the array is odd. If the length is even, subtracting 1 will yield an odd number and dividing that by 2 will not yield a whole number. Array indices must be integers and not floats. Using Math.floor() on the division gives a usable index regardless of whether the length is odd or even, and no subtraction by 1 is needed.
nice tip
Damn. And here I thought array access with non integer values was the same as in c++
yeah it's limited formula
C++ can do an implict conversion of float to int. JS only has number type, so no conversion happens.