-2

I am getting an array of data in Angularjs Grid and I need to delete all the rows which has same CustCountry

ex - My Customer Array looks like

  Customer[0]={ CustId:101 ,CustName:"John",CustCountry:"NewZealand" };
  Customer[1]={ CustId:102 ,CustName:"Mike",CustCountry:"Australia" };
  Customer[2]={ CustId:103 ,CustName:"Dunk",CustCountry:"NewZealand" };
  Customer[3]={ CustId:104 ,CustName:"Alan",CustCountry:"NewZealand" };

So , in the Grid I need to delete all three records if CustomerCountry is NewZealand

I am using splice method and let me know how can I use by splicing through CustomerCountry

 $scope.remove=function(CustCountry)
{
    $scope.Customer.splice(index,1);
 }
Rahul Sharma
  • 87
  • 1
  • 9

2 Answers2

2

If you're okay with getting a copy back, this is a perfect use case for .filter:

Customer = [
  { CustId:101 ,CustName:"John",CustCountry:"NewZealand" },
  { CustId:102 ,CustName:"Mike",CustCountry:"Australia" },
  { CustId:103 ,CustName:"Dunk",CustCountry:"NewZealand" },
  { CustId:104 ,CustName:"Alan",CustCountry:"NewZealand" },
]

console.log(Customer.filter(cust => cust.CustCountry !== "NewZealand"));
CRice
  • 29,968
  • 4
  • 57
  • 70
  • 2
    The important part to this that you're missing is `$scope.Customer = $scope.Customer.filter(...)` – Phil Dec 26 '17 at 23:09
0

if you have one specific country in mind then just use .filter()

$scope.Customer = $scope.Customer.filter(obj => obj.CustCountry !== "SpecificCountry")

If you want to delete all objects with duplicate countries then, referring to Remove duplicate values from JS array, this is what you can do:

var removeDuplicateCountries = function(arr){
    var dupStore = {};

    for (var x= 0; x < arr.length; x++){
        if (arr[x].CustCountry in dupStore){
            dupStore[arr[x].CustCountry] = false;
        } else {
            dupStore[arr[x].CustCountry] = true;
        }
    }


    var newarr = [];
    for (var x= 0; x < arr.length; x++){
        if (dupStore[arr[x].CustCountry]){
            newarr.push(arr[x]);
        }
    }

    return arr;
};
$scope.Customer = removeDuplicateCountries($scope.Customer);

Or incorporating the .filter() method

var removeDuplicateCountries = function(arr){
    var dupStore = {};
    var newarr = arr;

    for (var x= 0; x < arr.length; x++){
        if (arr[x].CustCountry in dupStore){
            newarr = newarr.filter(obj => obj.CustCountry !== arr[x].CustCountry);
        } else {
            dupStore[arr[x].CustCountry] = true;
        }
    }

    return newarr;
};
$scope.Customer = removeDuplicateCountries($scope.Customer);

if there are many duplicate countries then use the way without .filter()

Ayudh
  • 1,673
  • 1
  • 22
  • 55