簡體   English   中英

將一維數組的元素分組以在 Javascript 中形成鋸齒狀的二維數組

[英]Grouping elements of a 1D array to form a Jagged 2D array in Javascript

我的目標是選擇一維數組 B 的元素,根據它們在一維數組 B 中的位置將它們分組為子數組。它們在數組 B 中的位置(索引)在二維數組索引中提供。

 const B = [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.01, 1.1, 1.2, 1.5]; const indices = [ [ 3, 4, 5 ], [ 7, 8 ], [ 10, 11 ] ]; //Getting the elements from array B but flattened const arrs = []; for (let i = 0; i < indices.length; i++) { for (let j = 0; j < indices[i].length; j++) { arrs.push(B[indices[i][j]]); } } console.log("arrs", arrs) //Converting the flattened array to 2D var newArr = []; let k = indices.length while (k--) { newArr.push(arrs.splice(0, indices[k].length)); } console.log("newArr", newArr);

我所做的是使用嵌套的 for 循環來嘗試獲得所需的輸出,但數組 arrs 被展平了。 然后,我將扁平化的數組 arrs 轉換為二維數組 newArr。 有沒有更優雅、更直接的方法?

您可以在內部數組上使用.map()並將每個元素用作B數組的索引。 這仍然需要一個嵌套循環,因為您需要遍歷每個內部數組以及該內部數組中的每個元素:

 const B = [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.01, 1.1, 1.2, 1.5]; const indices = [ [ 3, 4, 5 ], [ 7, 8 ], [ 10, 11 ] ]; const newArr = indices.map( arr => arr.map(idx => B[idx]) ); console.log("newArr", newArr);

map()操作將做到這一點:

 const array = [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.01, 1.1, 1.2, 1.5]; const indices = [ [ 3, 4, 5 ], [ 7, 8 ], [ 10, 11 ] ]; const result = indices.map(a => a.map(i => array[i])); console.log(result);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM