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?

2

5 Answers 5

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));

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

1 Comment

@Michael, that's simple plain old JavaScript.
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/

Comments

1

how about the following:

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

Comments

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.

Comments

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.

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.