You can calculate the number of all elements contained in this two-dimensional array and find the index of 55 like this:
const arr = [[1,23,3,4,5],[3,4,5,6],[2,3,55,6]];
// 先扁平化为一维数组
const flatten = arr.flat();
// 计算总元素个数
const totalCount = flatten.length;
// 找到 55 的索引
const index = flatten.indexOf(55);
console.log(totalCount); // 13
console.log(index); // 6
The main steps:
- Flatten a two-dimensional array using Array.prototype.flat()
- Calculate the length of the flattened one-dimensional array, that is, the number of all elements
- Use indexOf on a one-dimensional array to find the position of 55
flat() can convert multi-dimensional arrays to one-dimensional, simplifying the problem to operate on one-dimensional arrays.
The indexOf() method can find the index of the element, returning -1 if it does not exist.
In this way, the total number of elements of the two-dimensional array and the position index of 55 can be easily calculated.