我正在努力遍歷陣列陣列并回傳一個帶有結果遞增值的新陣列。
這是概念:
let array1 = [array1, array2];
let array2 = [4000,5000,3000,6000];
let array3 = [3000, 15000, 9000, 1000];
let i = 0;
let newArray = []
while (i < array1.length) {
// how do I get the combined value in a new array so that newArray[0] = 7000, newArray[1] = 20000 etc.
}
Array1 來自 API,是未知數量的陣列。
uj5u.com熱心網友回復:
這應該適用于任意數量的子陣列。這里假設array1包含 4 個陣列。
let array2 = [4000, 5000, 3000, 6000]
let array3 = [3000, 15000, 9000, 500]
let array4 = [5000, 15000, 4000, 2000]
let array5 = [6000, 25000, 5000, 8000]
let array1 = [array2, array3, array4, array5]
const result = array1.reduce((acc, curr) => {
return acc.map((item, index) => item curr[index])
})
console.log(result)
參考:
.reduce.map
uj5u.com熱心網友回復:
如果元素數量是動態的,則
let array1 = [[4000, 5000, 3000, 6000], [3000, 15000, 9000, 1000, 2000, 3000], [1000], [3000, 15000, 9000, 1000, 2000, 3000, 1000, 10000]];
let index = 0;
let newArray = [];
let maxElements = Math.max(...array1.map(arr => arr.length));
let arrayLength = array1.length;
while (index < maxElements) {
let total = 0;
for (let arrayIndex = 0; arrayIndex < arrayLength; arrayIndex ) {
let element = array1[arrayIndex][index]
if (element) total = element;
}
newArray.push(total);
index ;
}
console.log(newArray)
uj5u.com熱心網友回復:
您可能需要一個嵌套回圈。因此,基本上您將迭代包含 array2 和 array3 的 array1,然后在 newArray 中您將查看特定索引是否具有值。如果是這樣,那么您將增加前一個的價值
let array2 = [4000, 5000, 3000, 6000];
let array3 = [3000, 15000, 9000, 1000];
let array1 = [array2, array3];
let i = 0;
let newArray = []
while (i < array1.length) {
for (let j = 0; j < array1[i].length; j ) {
// if index of new array is unoccupied then set a value there
if (!newArray[j]) {
newArray[j] = array1[i][j]
} else {
// if index is occupied then add with previous value
newArray[j] = newArray[j] array1[i][j]
}
}
i ;
}
console.log(newArray)
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/383230.html
標籤:javascript 数组
上一篇:如何制作缺口矩陣?
下一篇:提取符合條件的最后一項
