Reputation: 77
I have a multi-array (arr1) and an arrey (arr2)
var arr1 = [["Id", "Sku", "Name"], [10, "xxx", "yyy"], [20, "aaa", "eee"]];
var arr2 = ["Id", "Name"];
I would like that when the values in arr1[0] is not an element of the arr2 all the index value will be removed, so I will get this output:
var arr3 = if arr1[0] = arr2
console.log(arr3); // [["Id", "Name"], [10, "yyy"], [20, "eee"]];
Any help?
Upvotes: 0
Views: 26
Reputation: 52347
First, build a list of the indexes to remove by seeing if the key exists in arr2
. Then, return arr1
with those indexes filtered out of each element.
function filterUnusedElement(inputElement) {
const indexesToRemove = inputElement.reduce((acc, val, index) => arr2.includes(val) ? acc : [...acc, index], []);
return arr1.map(i => i.filter((_,index) => !indexesToRemove.includes(index)));
}
console.log(filterUnusedElement(arr1[0]));
// [["Id", "Name"], [10, "yyy"], [20, "eee"]]
Upvotes: 1