¿Cómo filtrar dos matrices?
Tengo dos matrices donde allBrands son todas las marcas y userBrands son marcas que el usuario ya seleccionó. Estoy tratando de filtrar allBrands de tal manera que no muestre las marcas ya seleccionadas por el usuario.
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, samsungPodemos usar find dentro del filter en lugar de map para encontrar si el usuario ya seleccionó la marca. Si la marca se encuentra en userBrands , devuelve falso, de lo contrario, devuelve verdadero dentro del filtro.
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); 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)Si está pensando en filtrar allBrands Array para que no contenga las marcas ya seleccionadas por el usuario. Puede intentar hacer 2 bucles for y anidar uno en el otro y recorrer la matriz allBrands para verificar si contiene la marca ya seleccionada por el usuario. Ejemplo:
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); } } }