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"))