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?
-
Dup? stackoverflow.com/questions/18303040/…,elclanrs– elclanrs2015年08月30日 07:57:31 +00:00Commented Aug 30, 2015 at 7:57
-
You can find your answer in [stackoverflow.com/questions/11076067/… [1]: stackoverflow.com/questions/11076067/…Arik Grinstein– Arik Grinstein2015年08月30日 07:58:37 +00:00Commented Aug 30, 2015 at 7:58
5 Answers 5
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));
1 Comment
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
how about the following:
var result = arrA.filter(function(elem){
return arrB.indexOf(elem) === -1;
);
Comments
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
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;
});
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.