Home > Mobile >  return all array if at least one element match
return all array if at least one element match

Time:04-25

using the following array of arrays I need to do a search for an element, if it finds that element it should return the entire array it belongs to

example

const data= [[
      "car",
      "plane",
      "boat"
  ],
  [
      "paris",
      "barcelona",
      "los angeles"
  ],
  [
      "milk",
      "eggs",
      "brea",
  ]
]

if match car must return

[plane, boat]

if match paris must return

[barcelona, los angeles]

CodePudding user response:

Find/Filter will return the array(s)

const data= [
  [ "car",   "plane",     "boat" ],
  [ "paris", "barcelona", "los angeles"],
  [ "milk",  "eggs",      "bread" ]
]
const findArr = (nestedArr, item) => nestedArr
  .find(arr => arr.includes(item))

const findAndExcludeItem = (nestedArr, item) => {
  const arrContaining = nestedArr.find(arr => arr.includes(item)) || []; // in case not found
  return arrContaining.filter(filteredItem => filteredItem != item);
};

const excludeArr = (nestedArr, item) => nestedArr
  .filter(arr => !arr.includes(item))



console.log(findArr(data,"paris"))
console.log(findAndExcludeItem(data,"paris"))
console.log(excludeArr(data,"paris"))

  • Related