'want to filter an array

I want to get an array with filtered values. My arrays are like,

let arr=[{name:'trt,tet', id:5},{name:td, id:25},{name:fxg, id:1},{name:fs, id:4},{name:ste, id:41}]

&

let arr1 =[{data:fxg, addr:po 87987},{data:tert, addr:po8798fvd7},{data:trt, addr:po 887},{data:trhd, addr:po 8798787}]

my resultant array that I want is,

let rslt =[data:tert, addr:po8798fvd7},{data:trhd, addr:po 8798787}]

that is in arr the object 'name' which is also in arr1 with name 'data' I don't need that array. nd some of which contain more than one name. I want to filter it.



Solution 1:[1]

try this

let arr=[{name:'trt,tet', id:5},{name:'td', id:25},{name:'fxg', id:1},{name:'fs', id:4},{name:'ste', id:41}]
let arr1 =[{data:'fxg', addr:'po 87987'},{data:'tert', addr:'po8798fvd7'},{data:'trt', addr:'po 887'},{data:'trhd', addr:'po 8798787'}]


const names = arr.flatMap(a => a.name.split(','))

const res = arr1.filter(a => !names.includes(a.data))

console.log(res)

Solution 2:[2]

This uses a Set which is optimized for lookups in O(1) and therefore the runtime of the algorithm is O(n) in contrast to using includes() which will result in a runtime of O(n²).

let arr = [
  { name: "trt", id: 5 },
  { name: "td", id: 25 },
  { name: "fxg", id: 1 },
  { name: "fs", id: 4 },
  { name: "ste", id: 41 },
];

let arr1 = [
  { data: "fxg", addr: "po87987" },
  { data: "tert", addr: "po8798fvd7" },
  { data: "trt", addr: "po887" },
  { data: "trhd", addr: "po8798787" },
];

// use array for quick lookups in O(1)
const set = new Set(arr.map(item => item.name));

// filter arr1 adding only items to result that are not in Set
const result = arr1.filter(item => !set.has(item.data))
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Mushroomator