-2

Let's say that I have the following multidimensional array :

const arrayOfValues = [
  ['a', 'b', 'c'],
  ['a', 'c'],
  ['c']
];

I would like to create a new array containing only the values that are present at every index of my original multidimensional array. So I would end up with the following array in this case :

['c']

I'm having trouble finding a way to do so as I am not too familiar with javascript. I'm guessing I have to apply some sort of filtering (probably map over the array and apply a specific condition) but I'm not sure how to go about it.

0

2 Answers 2

2

You can use Array#reduce along with Array#filter.

const arr = [
  ['a', 'b', 'c'],
  ['a', 'c'],
  ['c']
];
let res = arr.reduce((acc,curr)=>acc.filter(x=>curr.includes(x)));
console.log(res);

Sign up to request clarification or add additional context in comments.

Comments

0

Start with a persistent variable that starts with the values in the first subarray. Then iterate over each other subarray, reassigning that variable to a filtered version of the subarray currently being iterated over, filtering by whether the item is contained both in the previous subarray and the current one:

const arrayOfValues = [
  ['a', 'b', 'c'],
  ['a', 'c'],
  ['c']
];

let previous = arrayOfValues[0];
arrayOfValues.slice(1).forEach((subarr) => {
  previous = subarr.filter(
    item => previous.includes(item)
  );
});
console.log(previous);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.