0

I have this two integers arrays: I am working on my Angularjs tutorial project.

In controller I have this two arrays:

var arrA=[12,54,76,98,45];
var arrB=[12,98];

I need to delete from arrA all numbers that inside arrB.

arrA have to be like this after implementation:

arrA=[54,76,45]

What is best and elegantic way to implement it in angularjs?

Michael
  • 13,950
  • 57
  • 145
  • 288
  • Dup? http://stackoverflow.com/questions/18303040/how-to-remove-elements-nodes-from-angular-js-array, – elclanrs Aug 30 '15 at 07:57
  • You can find your answer in [http://stackoverflow.com/questions/11076067/finding-matches-between-multiple-javascript-arrays][1] [1]: http://stackoverflow.com/questions/11076067/finding-matches-between-multiple-javascript-arrays – Arik Grinstein Aug 30 '15 at 07:58

5 Answers5

3

You can use Array.prototype.filter() in conjunction with Array.prototype.indexOf()

The filter() method creates a new array with all elements that pass the test implemented by the provided function.

The indexOf() method returns the first index at which a given element can be found in the array, or -1 if it is not present.

var arrA=[12,54,76,98,45];
var arrB=[12,98];

arrA = arrA.filter(function(o){
  return arrB.indexOf(o) == -1;
  });

document.write(JSON.stringify(arrA));
Satpal
  • 132,252
  • 13
  • 159
  • 168
1

Off the top of my head.

//Run a loop to go through all elements in arrB
for (var i=0;i<arrB.length;i++) {
   //keep position of element i in arrA
   //if it's not there index will be equal to -1
   var index=arrA.indexOf(arrB[i])
   //if it is there
   if(index!=-1) {
   //remove 1 element at position index from arrA
    arrA.splice(index,1)
   }
}

Good luck. This has nothing to do with angular btw, it's basic javascript.

Here's a fiddle: https://jsfiddle.net/MichaelSel/t2dfg31c/

Michael Seltenreich
  • 3,013
  • 2
  • 29
  • 55
1

Angular doesn't concern itself with things like array manipulation. JavaScript provides facilities for that though:

var diff = arrA.filter(function(item) {
    return arrB.indexOf(item) < 0;
});

Fiddle

If arrB is very large, you might want to allow it to be O(N) (for smallish ones) up to O(N log N), instead of O(n^2):

var lookup = arrB.reduce(function(lookup, item) {
    lookup[item] = true;
    return lookup;
}, {});
diff = arrA.filter(function(item) {
    return !Object.prototype.hasOwnProperty.call(lookup, item);
});

However, this only works if the string representation of the item is what you are looking at. It would work for integers.

doug65536
  • 6,562
  • 3
  • 43
  • 53
1

how about the following:

var result = arrA.filter(function(elem){
  return arrB.indexOf(elem) === -1;
);
1

To delete items from any array you need to use splice:

$scope.items.splice(index, 1);

now what you can do is, you can run a for loop to identify the duplicate element. Once identified you can remove it using splice function.

Rob
  • 169
  • 2
  • 4
  • 15