Sony ThePony Sony ThePony - 3 months ago 12
Javascript Question

Use index array to filter another array

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.

Answer

you can use the benefit of Array.filter 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

Array.filter callback will be executed in each loop on where you used this function (on above example, it used on arr variable).

It'll pass two arguments, first is the element, and the second is the index. because you need the value of index, you have to write all those two arguments, even you won't use the first argument (eachElem).

In this issue, the index variable is used to determine wether it exists on the foundIn variable or not (we use Array.indexOf to do the checking). If it's not exists, true will be given. So all returned element is the one which is not exists on the foundIn.

Array.indexOf will return the index when the searched item is exists. Otherwise it'll return -1.


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"]