Nicoleta Wilskon
Nicoleta Wilskon

Reputation: 697

Splicing one array with another array values

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.

Upvotes: 0

Views: 194

Answers (2)

taguenizy
taguenizy

Reputation: 2265

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

Upvotes: 2

Mistalis
Mistalis

Reputation: 18279

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"]

Upvotes: 0

Related Questions