Issue
I have two arrays
arr = [ aaa, xxx, aaa, xxx, aaa ];
foundIn = [ 1, 3 ];
As you can see foundIn has the index numbers of arr that I would like to remove. How can I remove the values in arr using the the index values in foundIn
The output being: newArr = [ aaa, aaa, aaa ];
This is a simplified version of my issue.
Any help in this would be greatly appreciated.
Solution
You can utilize the native javascript .filter()
method to solve this kind of problem.
var arr = ["aaa", "xxx", "aaa", "xxx", "aaa"];
var foundIn = [1, 3];
var res = arr.filter(function (eachElem, index) {
return foundIn.indexOf(index) == -1
})
console.log(res) // ["aaa", "aaa", "aaa"]
Explanation
The callback will be executed in each loop on where this function is called (in the example above example, it will be used on arr
variable).
Two arguments are passed into the callback. First is the element, and the second is the index. Because you need the index
, you have to write all those two arguments, even though you are not using the first argument.
In this issue, the index
variable is used to determine whether it exists on the foundIn
variable or not (we use .indexOf()
method to do the checking). If it’s not exists, true
will be given. So all returned element is the one which is not exists in the foundIn
.
.indexOf()
returns the index of the searched item, if it’s not found, -1
is returned.
If you are using es6, you can simplify the code:
var res = arr.filter((d, i) => foundIn.indexOf(i) == -1)
Also try this working example:
var arr = ["aaa", "xxx", "aaa", "xxx", "aaa"];
var foundIn = [1, 3];
var res = arr.filter(function (eachElem, index) {
return foundIn.indexOf(index) == -1
})
document.write(JSON.stringify(res))
// ["aaa", "aaa", "aaa"]
Answered By – novalagung
This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0