How to calculate the number of elements (including sub-elements) contained in the list [[1,23,3,4,5],[3,4,5,6],[2,3,55,6]]. And the returned 55 is the first element

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:

  1. Flatten a two-dimensional array using Array.prototype.flat()
  2. Calculate the length of the flattened one-dimensional array, that is, the number of all elements
  3. 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.

Guess you like

Origin blog.csdn.net/bulucc/article/details/132345267