Home > Software engineering >  How to filter two arrays?
How to filter two arrays?

Time:04-23

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

CodePudding user response:

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

CodePudding user response:

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)

CodePudding user response:

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);
    }
  }
}

  • Related