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?
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));
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/
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.
how about the following:
var result = arrA.filter(function(elem){
return arrB.indexOf(elem) === -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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.