2016-10-28 58 views
-1

陣列我有這樣如何分離在JavaScript

 dta: [ 
     { 
      amt: "200000", 
      dat: "2016-10-14 10:41:20 am", 
      grt: "GRT", 
      uid:"example123" 
     }, 
     { 
      amt: "300000", 
      dat: "2016-10-14 10:41:20 am", 
      grt: "RPD", 
      uid:"example123" 
     }] 

陣列對象,並我要拆分此陣列中的兩個陣列基於所述基於所述grt:

我試過,但它開始從1

function seperate(data) { 
console.log(data) 
for (var i = 0; i < data.dta.length; i++) { 
     if (data.dta[i].grt === 'GRT') { 
      owing[i] = data.dta[i]; 
     } else { 
      repaid[i] = data.dta[i]; 
     } 
    } 
} 
+0

通過調試器走過你的代碼,你會很快看到你的問題在哪裏。 – 2016-10-28 09:41:16

+1

可能重複[什麼是最有效的方法groupby在一個JavaScript數組的對象?](http://stackoverflow.com/questions/14446511/what-is-the-most-efficient-method-to-groupby- on-a-javascript-array-of-objects) –

回答

-1

嘗試secong數組索引:

function seperate(data) { 
console.log(data) 
for (var i = 0; i < data.dta.length; i++) { 
     if (data.dta[i].grt === 'GRT') { 
      owing.push(data.dta[i]); 
      // console.log(owing[i] + i); 
     } else { 
      repaid.push(data.dta[i]) 
      // console.log(repaid[i] + i); 
     } 
    } 
} 

.push將新元素添加到給定數組的末尾。 Documentation。用例:

var a = [1, 2, 3]; 
a.push(4, 5); 

console.log(a); // [1, 2, 3, 4, 5] 

您當前的解決方案創建兩個陣列中,每個長度(幾乎)等於輸入數組,但與許多在其中的孔。例如,考慮(簡化的)輸入陣列如下:

['GRT', 'RPD', 'GRT', 'RPD', 'GRT', 'RPD'] 

你的溶液創建兩個陣列是這樣的:

['GRT' , undefined, 'GRT' , undefined, 'GRT'] 
[undefined, 'RPD' , undefined, 'RPD' , undefined, 'RPD'] 

使用push代替創建兩個陣列是這樣的:

['GRT', 'GRT', 'GRT'] 
['RPD', 'RPD', 'RPD'] 
+0

Downvoter:如何改進答案? – Oliver

+0

不是我的dv,但是你可以用一些更通用的代碼替換'GRT'上的檢查。 – msfoster

0

您的代碼正在增加與數組無關的索引。所以不管哪一個陣列被更新使用索引爲兩個陣列是由1

遞增您可以具有對於每個陣列獨立的索引變量,或者您可以利用陣列forEachpush功能如下所示。

var owing = []; 
var repaid = []; 
function seperate(data) { 
    data.dta.forEach(function(d) { 
     if (d.grt === 'GRT') { 
      owing.push(d); 
     } else { 
      repaid.push(d); 
     } 
    }); 
} 
+0

爲什麼downvote? – H77