0

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?

1
  • Use .map() and .filter() Commented Mar 29, 2021 at 19:19

1 Answer 1

1

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"]]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.