Learning Learning - 2 months ago 11
AngularJS Question

How to compare all nested child elements length with each other?

I have 1 object which contains nested child like below:

$scope.artists.materials.items[] //contains list of items


Now i would have several artist which will contains list of items but in this i want to check total length of each item of artists and if mismatch found then i want to return true or false.

For eg: I have 2 artist and from this Artist1 contains 2 items and Artist2 contains only 1 item then this is a mismatch as i want to have both the artist to contains same number of items.

But here i am confused with how do i do all this comparision in angular js way.

Code:

function checkItemsValidity() {
angular.forEach($scope.artists, function (artist) {
alert(artist.materials.items.length);
});
}


Can anybody please help me how to do this in better way ??

Lex Lex
Answer

If all artists have to have the same number of items, then just store the length of the items from the first artist and make sure all of them have that same items length. Something like:

Updated with suggestions from comments

function checkItemsValidity() {
    var itemsLength = $scope.artists[0].materials.items.length;
    angular.forEach($scope.artists, function (artist) {
        if(artist.materials.items.length != itemsLength) {
            return false;
        }
    });
    return true;
}
Comments