Learning Learning - 1 month ago 5
AngularJS Question

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??

Answer

Since all artists need to have the same number of materials...

function checkMaterials (arists)
{
  if (!artists || !artists.length) { return false; }
  if (artists.length < 2)          { return true; }

  var valid = true;
  var materialCount

  try
  {
    //All artists must have the same number of materials, so we
    //can test against the number of materials that the first
    //artist has and reduce the number times we access the object
    materialCount = (artists[0].materials.items || []).length;
  }
  catch (exception)
  {
    //Object is malformed
    return false;
  }

  //Loop through the remaining artists and check how
  //many materials they have against the first artist
  for (var i = 1; i < artists.length; i++)
  {
    if (!artists[i].materials || ((artists[i].materials.items || []).length !== materialCount)
    {
      //Once one failed case is found, we can stop checking
      valid = false;
      break;
    }
  }

  return valid;
}

//Test data
var validArtists = [{
  materials: {
    items: [1, 2, 3]
  }
}, {
  materials: {
    items: [1, 3, 4]
  }
}];

var invalidArtists = [{
  materials: {
    items: [1, 2]
  }
}, {
  materials: {
    items: [3]
  }
}];

//Tests
console.log (checkMaterials (validArsists)); //Prints true
console.log (checkMaterials (invalidArtists)); //Prints false
Comments