How to get item index in a single-dimension array using row and column? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 3

How to get item index in a single-dimension array using row and column?

I have a single-dimension array that contains items from a grid. Each item in the array contains the values of which row and column it occupies in the grid. What I need to do is to obtain the index of said item in the single-dimension array using its row and column. In other words, I need to map the row and column with the index of the item in the single-dimension array. How do I achieve that? [Details] The array is a HTMLCollection containing 64 div elements which are inside another div with display=grid. The grid size (rows, cols) is 8x8. I get said item when it's clicked. I retrieve the row and column of that item in the grid container. [Example] If item's row = 0 and col = 3, the index of that item in the single-dimension array is 3. If row = 1 and col = 1, index must be 19. Thanks in advance.

18th Dec 2020, 3:04 PM
Erick Ruh Cardozo
Erick Ruh Cardozo - avatar
5 Answers
+ 1
A simple solution would be converting my array which is an HTMLCollection with Array.from() and call indexOf(item). But that would not be good for performance, since indexOf would loop the whole array to find the index of said item. I know that there's a mathematical formula to do that map. Hence, I would be able to access the item directly in the array by its index and avoid looping the whole array to then access it.
18th Dec 2020, 3:24 PM
Erick Ruh Cardozo
Erick Ruh Cardozo - avatar
+ 1
And just in case someone is curious about what I am doing: I'm making a checkers game, and when the piece is selected I need to highlight the cells it can move to. That's why I need this conversion thing. I'm not interested in obtain the item itself, but rather its index to find out the cells the piece can move to.
18th Dec 2020, 3:27 PM
Erick Ruh Cardozo
Erick Ruh Cardozo - avatar
+ 1
Spentify Thank you very much for your answer. Technically what I need is the opposite: from a given row and column indexes obtain the (single-dimension) index. However, I know that some point in time I'll need to map the single-dimension index to row and column, so thanks again. Any clue on how to do the opposite?
18th Dec 2020, 4:57 PM
Erick Ruh Cardozo
Erick Ruh Cardozo - avatar
+ 1
HELL YEAH BRO! This simple (almost stupid) thing is bothering me all day. God bless you dude!
18th Dec 2020, 10:17 PM
Erick Ruh Cardozo
Erick Ruh Cardozo - avatar
0
Hello dear
19th Dec 2020, 7:12 AM
Pelumi Bello
Pelumi Bello - avatar