Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Not able to validate all nested child elements length

I have 1 object which contains nested child like below:

$scope.artists.materials.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.

Problem is when i dont have items for any of the artist then still i am getting false

Idea here is to store the length of the items from the first artist and make sure all of them have that same items length.

Code:

function checkItemsValidity() {
      for (var i = 1; i < $scope.artists.length; index++) {
            if ($scope.artists[i].materials.items != undefined && $scope.artists[0].materials.items) {
                if($scope.artists[i].materials.items.length != $scope.artists[0].materials.items[0].length) {
                             return false;
                }
            }        
                             return false;
        }
            return true;
    }

Case 1:In case of only 1 artist then return true becuase no other artist to compare

Case 2: In case of 2 artist with 2 items for both artist return true else false;

Case 3: In case of 3 artist with 2 items for artist1 and artist 2 and 5 items for artist3 then return false;

Can anybody please hlep me with this??

like image 223
Learning-Overthinker-Confused Avatar asked Dec 19 '22 13:12

Learning-Overthinker-Confused


1 Answers

As I understand you just want to check if every artist has the same number of items. This code:

var result, materialsNumber;
for (var artist of $scope.artists) {
   var artistMaterialsNumber = artist.materials.items.length;
   if (!materialsNumber) {
       materialsNumber = artistMaterialsNumber;
   }
   result = (materialsNumber === artistMaterialsNumber);
   if (!result) {
      break;
   }
}

return result;

should be useful for that. It remembers number of items of first artist and checks if every other artist has same number of items. In case there is artist with different item number code breaks and returns false.

like image 160
GROX13 Avatar answered Jan 13 '23 18:01

GROX13