DaviesTobi alex DaviesTobi alex - 1 month ago 5
Javascript Question

How to Separate an array in javascript

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

Answer

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']