0

I have a function displaySelectedRole() and I have variables $scope.Role and $scope.rolenames .I need to remove all values available in $scope.role from $scope.rolename.

$scope.role= ["A","B","C"]; 

$scope.rolename =["A","B","C","D","E"]

I need to splice the values and get $scope.rolename = ["D","E"]

$scope.displaySelectedRole = function(role, index) {
           debugger;
           $scope.role.splice(RoleNames[index]);
            console.log($scope.role);

I tried to use splice based on index , but problem is it given empty array values in console.

1
  • 1
    $scope.rolename.filter(x=>!$scope.role.includes(x)) Commented Oct 28, 2016 at 9:27

2 Answers 2

2

You can use filter

var $scope = {};  // Ignore this line
$scope.role= ["A","B","C"]; 
$scope.rolename = ["A","B","C","D","E"];

$scope.rolename = $scope.rolename.filter(function(role){
   return $scope.role.indexOf(role) === -1;
})

console.log($scope.rolename);

If you want to remove them directly you could iterate through the $scope.role and use splice

   var $scope = {};  // Ignore this line
   $scope.role= ["A","B","C"]; 
   $scope.rolename = ["A","B","C","D","E"];

   $scope.role.forEach(function(role){
   var index = $scope.rolename.indexOf(role);
   if(index !== -1) $scope.rolename.splice(index, 1);
})

console.log($scope.rolename);

Note: Array.filter will return a new array, unlike array.splice which will modify original array.

Reference

Sign up to request clarification or add additional context in comments.

Comments

0

You can you Underscore.js's difference(), it purposes a method to substract arrays:

$scope.role = ["A","B","C"]; 
$scope.rolename = ["A","B","C","D","E"];
$scope.diff = _.difference($scope.rolename, $scope.role); // ["D","E"]

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.