Skip to content
Advertisement

How to filter array with children are array?

Fillter in an array

const words = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present'];

const result = words.filter(word => word.includes('e'));

console.log(result);
// expected output: Array ["elite", "exuberant", "destruction", "present"]

But if an array consists of many arrays inside, I am not finding a reasonable way to solve it.

Example: with this array

const array = [
  ["aaaa", "b", "c", "d", "e", "f", "g"],
  ["h", "i", "j", "k", "l", "m", "n"],
  ["haaaa", "i", "j", "k", "laaaa", "m", "naaaa"],
  ["o", "o", "o", "o", "o", "o"],
];

How to fillter ‘a’ and get result

result = [
  ["aaaa", "b", "c", "d", "e", "f", "g"],
  ["haaaa", "i", "j", "k", "laaaa", "m", "naaaa"],
];

Advertisement

Answer

Use filter and some

const data = [
    ["aaaa", "b", "c", "d", "e", "f", "g"],
    ["h", "i", "j", "k", "l", "m", "n"],
    ["haaaa", "i", "j", "k", "laaaa", "m", "naaaa"],
    ["o", "o", "o", "o", "o", "o"],
];

const output = data.filter((arr) => arr.some((item) => item.includes("a")));

console.log(output);
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement