簡體   English   中英

如何將數組數組中相同索引處的元素加到一個數組中?

[英]How to sum elements at the same index in array of arrays into a single array?

假設我有一個數組數組,如下所示:

[
  [0, 1, 3],
  [2, 4, 6],
  [5, 5, 7],
  [10, 0, 3]
]

如何生成一個新數組,將javascript中內部數組每個位置的所有值相加? 在這種情況下,結果將是:[17,10,19]。 無論內部數組的長度如何,我都需要能夠有一個可行的解決方案。 我認為這可以使用 map 和 for-of 的某種組合,或者可能減少,但我不能完全理解它。 我已經搜索過,但找不到任何與此完全匹配的示例。

您可以將Array.prototype.reduce()Array.prototype.forEach()結合使用。

 var array = [ [0, 1, 3], [2, 4, 6], [5, 5, 7], [10, 0, 3] ], result = array.reduce(function (r, a) { a.forEach(function (b, i) { r[i] = (r[i] || 0) + b; }); return r; }, []); document.write('<pre>' + JSON.stringify(result, 0, 4) + '</pre>');

更新,一種更短的方法,通過使用映射來減少數組。

 var array = [[0, 1, 3], [2, 4, 6], [5, 5, 7], [10, 0, 3]], result = array.reduce((r, a) => a.map((b, i) => (r[i] || 0) + b), []); console.log(result);

使用Lodash 4

 function sum_columns(data) { return _.map(_.unzip(data), _.sum); } var result = sum_columns([ [1, 2], [4, 8, 16], [32] ]); console.log(JSON.stringify(result));
 <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.js"></script>

對於較舊的 Lodash 版本和一些備注

Lodash 4 改變了_.unzipWith工作方式,現在 iteratee 一次獲取所有作為擴展參數傳遞的值,所以我們不能再使用 reducer 樣式_.add了。 使用Lodash 3 ,以下示例可以正常工作:

 function sum_columns(data) { return _.unzipWith(data, _.add); } var result = sum_columns([ [1, 2], [4, 8, 16], [32], ]); console.log(JSON.stringify(result));
 <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/3.10.1/lodash.js"></script>

_.unzipWith將在行比其他行短的地方插入undefined s,並且_.sum將 undefined 值視為 0。(從 Lodash 3 開始)

如果您的輸入數據可以包含undefinednull項,並且您希望將它們視為 0,則可以使用以下命令:

 function sum_columns_safe(data) { return _.map(_.unzip(data), _.sum); } function sum_columns(data) { return _.unzipWith(data, _.add); } console.log(sum_columns_safe([[undefined]])); // [0] console.log(sum_columns([[undefined]])); // [undefined]
 <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/3.10.1/lodash.js"></script>

這個片段適用於 Lodash 3,不幸的是我沒有找到一種在 Lodash 4 中將 undefined 視為 0 的好方法,因為現在 sum 已更改,因此_.sum([undefined]) === undefined

ES6的單行,帶有mapreduce

 var a = [ [0, 1, 3], [2, 4, 6], [5, 5, 7], [10, 0, 3] ]; var sum = a[0].map((_, i) => a.reduce((p, _, j) => p + a[j][i], 0)); document.write(sum);

假設嵌套數組總是具有相同的長度,可以使用 concat 和 reduce。

 function totalIt (arr) { var lng = arr[0].length; return [].concat.apply([],arr) //flatten the array .reduce( function(arr, val, ind){ //loop over and create a new array var i = ind%lng; //get the column arr[i] = (arr[i] || 0) + val; //update total for column return arr; //return the updated array }, []); //the new array used by reduce } var arr = [ [0, 1, 3], [2, 4, 6], [5, 5, 7], [10, 0, 3] ]; console.log(totalIt(arr)); //[17, 10, 19]

假設數組是靜態的,如圖所示。

 a = [ [0, 1, 3], [2, 4, 6], [5, 5, 7], [10, 0, 3] ] b = [] for(i = 0; i < a[0].length; i++){ count = 0 for(j = 0; j < a.length; j++){ count += a[j][i] } b.push(count) } console.log(b)

到目前為止,沒有使用問題for ... of提到的for ... of答案。
我對不同長度的內部數組使用了條件語句。

 var a = [ [0, 1, 3], [2, 4, 6], [5, 5, 7], [10, 0, 3] ]; i = 0; r = [] for (const inner of a) { j = 0; for (const num of inner) { if (j == r.length) r.push(num) else r[j] += num j++; } i++; } console.log(r);

誠然,在這種情況下,經典的for cycle 比for ... of更適合。
以下代碼段使用條件(三元)運算符。

 var a = [ [0, 1, 3], [2, 4, 6], [5, 5, 7], [10, 0, 3] ]; r = []; for (i = 0; i < a.length; i++) { for (j = 0; j < a[i].length; j++) { j==r.length ? r.push(a[i][j]) : r[j]+=a[i][j] } } console.log(r);

使用映射和歸約的解決方案,從不同長度的數組中添加元素。

 var array = [ [0], [2, 4], [5, 5, 7, 10, 20, 30], [10, 0] ]; b = Array(array.reduce((a, b) => Math.max(a, b.length), 0)).fill(0); result = array.reduce((r, a) => b.map((_, i) => (a[i] || 0) + (r[i] || 0)), []); console.log(result);

const ar = [
  [0, 1, 3],
  [2, 4, 6],
  [5, 5, 7],
  [10, 0, 3]
]   

ar.map( item => item.reduce( (memo, value)=> memo+= value, 0 ) )
//result-> [4, 12, 17, 13]

暫無
暫無

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

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