Gayathri Mohan
Gayathri Mohan

Reputation: 2962

check array inside an array length is empty then remove the parent array from the main array

Hi How to check array inside an array length is empty then remove the parent array from the main array ,

think about i have an array

[
    {
        "id": 71,
        "campaignAssets": [
            {
                "id": 128
            }
        ]
    },
    {
        "id": 99,
        "campaignAssets": []
    }
]

from above array id:71 have campaignAssets array which is length is 1 but on the other one "id": 99 dont have the campaignAssets so i have to remove the parent array which means

    {
        "id": 99,
        "campaignAssets": []
    }

so final array should be

[
    {
        "id": 71,
        "campaignAssets": [
            {
                "id": 128
            }
        ]
    }
]

Upvotes: 0

Views: 90

Answers (2)

Nina Scholz
Nina Scholz

Reputation: 386756

This proposal features two solutions,

  1. generate a new array and assign it to the original array
  2. delete unwanted items without generating a temporary.

1. With a new array

You could filter it with Array#filter

var data = [{ "id": 71, "campaignAssets": [{ "id": 128 }] }, { "id": 99, "campaignAssets": [] }];

data = data.filter(function (a) { return a.campaignAssets.length; });

console.log(data);

In ES6 it's even shorter

var data = [{ "id": 71, "campaignAssets": [{ "id": 128 }] }, { "id": 99, "campaignAssets": [] }];

data = data.filter(a => a.campaignAssets.length);

console.log(data);

2. Without a new array

For a in situ solution, keeping the array and delete only the elements with zero length, I suggest to use backward iteration and check the length and use Array#splice accordingly.

var data = [{ "id": 71, "campaignAssets": [{ "id": 128 }] }, { "id": 99, "campaignAssets": [] }],
    i = data.length;

while (i--) {
    if (!data[i].campaignAssets.length) {
        data.splice(i, 1);
    }
}

console.log(data);

Upvotes: 6

A.T.
A.T.

Reputation: 26342

var data =[
    {
        "id": 71,
        "campaignAssets": [
            {
                "id": 128
            }
        ]
    },
    {
        "id": 99,
        "campaignAssets": []
    }
]
var i = data.length;
while (i--) {
    if(data[i].hasOwnProperty('campaignAssets') && data[i]['campaignAssets'].length==0)
       data.splice(i, 1)
}

// This one is wrong implementation as pointed out, it will not delete element from reducing array..
// data.forEach(function(parent,index){
//  if(parent.hasOwnProperty('campaignAssets') && parent['campaignAssets'].length==0)
//       data.splice(index, 1)
// });

console.log(data);

Upvotes: 0

Related Questions