Simple Array question

how to print first, middle and last items of this array with a clean code?
No description
11 Replies
Jochem
Jochem11mo ago
does the homework assignment state whether it's always an odd number of elements?
3moor_m
3moor_m11mo ago
No it just asks to print first, middle and last items
Jochem
Jochem11mo ago
do you know how to access an item in an array?
ChooKing
ChooKing11mo ago
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.
3moor_m
3moor_m11mo ago
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 )
Jochem
Jochem11mo ago
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 be
ChooKing
ChooKing11mo ago
This 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.
3moor_m
3moor_m11mo ago
nice tip
Senra
Senra11mo ago
Damn. And here I thought array access with non integer values was the same as in c++
3moor_m
3moor_m11mo ago
yeah it's limited formula
ChooKing
ChooKing11mo ago
C++ can do an implict conversion of float to int. JS only has number type, so no conversion happens.