-1

I have an array object like this

      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"
        }]

and I wish to split this array in two arrays based on the based on the grt:

I tried this but it starts the secong array index from 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];
       }
   }
}
Oliver
  • 11,297
  • 18
  • 71
  • 121
DaviesTobi alex
  • 610
  • 1
  • 9
  • 34
  • Walk though your code with a debugger, and you will quickly see where your problem lies. –  Oct 28 '16 at 09:41
  • 1
    Possible duplicate of [What is the most efficient method to groupby on a javascript array of objects?](http://stackoverflow.com/questions/14446511/what-is-the-most-efficient-method-to-groupby-on-a-javascript-array-of-objects) – Krzysztof Safjanowski Oct 28 '16 at 09:54

2 Answers2

0

Your code is increasing the index independent of the array. So regardless of which array is being updated the index you use for both arrays is incremented by 1.

You can either have separate index variables for each array or you can make use of array forEach and push functions as shown below.

var owing = [];
var repaid = [];
function seperate(data) {
    data.dta.forEach(function(d) {
        if (d.grt === 'GRT') {
            owing.push(d);
        } else {
            repaid.push(d);
        }
    });
}
H77
  • 5,859
  • 2
  • 26
  • 39
-1

Try:

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 adds new elements to the end of a given array. Documentation. Usage example:

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

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

Your current solution creates two arrays, each of length (almost) equal to the input array, but with lots of holes in them. For instance, consider the (simplified) input array as follows:

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

Your solution creates two arrays like this:

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

Using push instead creates two arrays like this:

['GRT', 'GRT', 'GRT']
['RPD', 'RPD', 'RPD']
Oliver
  • 11,297
  • 18
  • 71
  • 121