1

I am trying to compare 2 objets using underscore, specifically I am trying to compare the key/values of "id" (because other things inside will change). I basically want to just check if object A has an item that object B does not have, remove it from object A. Here is my attempt at it :

for(var c=0;c<$scope.types.length;c++){
    var real = _.some($scope.storeTempName, function(it) {
        return it.id == $scope.types[c].typeId; 
    });
    if(real){
    }else{  
        $scope.types.splice(c,1);
    }
}

Where $scope.storeTempName is object B and $scope.types is object A. So if $scope.types has something $scope.storeTempName does not, remove it (tracking by id and typyId for types).

This first attempt I have works, BUT it only will remove the first one. My guess is it's becasue I'm looping from 0 ++ and the index's are changing when i remove the first one so splice is targetting a false item. I am not sure though, and could use some help. Thank you for reading!

3
  • Your code would be significantly more readable if you just assigned $scope.......................types to something. Commented Dec 5, 2014 at 13:03
  • Do you need to use .splice() because of angular's data-binding? You could just use a filter otherwise. Commented Dec 5, 2014 at 13:15
  • @sacho I Don't need to use splice no, can you filter 2 objects against each other based off 2 different keys? Commented Dec 5, 2014 at 13:17

1 Answer 1

1

Just use _.filter.

$scope.types = _.filter($scope.types, function (type) {
    return _.some($scope.storeTempName, function (it) { return it.id == type.typeId })
})
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.