Home > Software design >  search in array of array, and return results in one array
search in array of array, and return results in one array

Time:05-19

using the following array of arrays I need to make a search by letter, if it finds that element it should return in one array

example

const data= [[
      "car",
      "plane",
      "boat"
  ],
  [
      "cartago",
      "barcelona",
      "los angeles"
  ],
  [
      "headphone",
      "phone",
      "camera",
  ]
]

if match "ca" must return

[car, cartago, camera]

if match "ne" must return

[plane, headphone, phone]

CodePudding user response:

flat the array and filter it by checking if the substring is included in each element

const data= [[      "car",      "plane",      "boat"  ],  [      "cartago",      "barcelona",      "los angeles"  ],  [      "headphone",      "phone",      "camera",  ]]

let a = data.flat().filter(v => v.includes('ca'))
console.log(a)

let b = data.flat().filter(v => v.includes('ne'))
console.log(b)

  • Related