-1

How to filter two arrays?

I have two arrays where allBrands are all brands and userBrands are brands that the user has already selected, I'm trying to filter allBrands in such a way that it doesn't show the brands already selected by the user

  const allBrands = [
    { id: 0, title: "Apple" },
    { id: 1, title: "bmw" },
    { id: 2, title: "mercedes" },
    { id: 3, title: "samsung" }
  ];
  const userBrands = [
    { id: 0, title: "Apple" },
    { id: 1, title: "mercedes" }
  ];

  const filtered = allBrands.filter(({ title }) => {
    return userBrands.map((item) => item.title !== title);
  }); // need bmw, samsung
trickysneak
  • 65
  • 1
  • 6
  • Does this answer your question? [How to filter an array from all elements of another array](https://stackoverflow.com/questions/34901593/how-to-filter-an-array-from-all-elements-of-another-array) – Vega Apr 23 '22 at 04:04

3 Answers3

1

We can use find inside the filter instead of map to find if the brand is already selected by the user. If brand is found in userBrands then return false, else return true inside filter.

const allBrands = [
  { id: 0, title: "Apple" },
  { id: 1, title: "bmw" },
  { id: 2, title: "mercedes" },
  { id: 3, title: "samsung" }
];
const userBrands = [
  { id: 0, title: "Apple" },
  { id: 1, title: "mercedes" }
];

const filtered = allBrands.filter(({ title }) => {
  return !userBrands.find((item) => item.title === title);
}); // need bmw, samsung

console.log(filtered);
PR7
  • 1,524
  • 1
  • 13
  • 24
1

const allBrands = [
    { id: 0, title: "Apple" },
    { id: 1, title: "bmw" },
    { id: 2, title: "mercedes" },
    { id: 3, title: "samsung" }
  ];
  const userBrands = [
    { id: 0, title: "Apple" },
    { id: 1, title: "mercedes" }
  ];

  
  
  const filtered = allBrands.filter(({ title:title1 }) => !userBrands.some(({ title:title2 }) => title1 === title2));
  
  console.log(filtered)
DengSihan
  • 2,119
  • 1
  • 13
  • 40
0

If you are thinking of filtering the allBrands Array so that it does not contain the brands already selected by the user. You can try making 2 for loops and nesting one in the other and cycling through the allBrands array to check if it contains the brand already selected by the user. Example:

const allBrands = [
    { id: 0, title: "Apple" },
    { id: 1, title: "bmw" },
    { id: 2, title: "mercedes" },
    { id: 3, title: "samsung" }
  ];
  const userBrands = [
    { id: 0, title: "Apple" },
    { id: 1, title: "mercedes" }
  ];
 
 //Filtering Part
 for(let i = 0; i < allBrands.length; i++) {
  for(let j = 0; j < userBrands.length; j++) {
    if(allBrands[i] === userBrands[j]) {
        allBrands.slice(i, 1);
    }
  }
}
Ryan M
  • 18,333
  • 31
  • 67
  • 74
Blogs Hub
  • 1
  • 2