如何過濾兩個陣列?
我有兩個陣列,其中 allBrands 是所有品牌,而 userBrands 是用戶已經選擇的品牌,我試圖過濾 allBrands,使其不顯示用戶已經選擇的品牌
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
uj5u.com熱心網友回復:
我們可以使用findinsidefilter來map查找品牌是否已被用戶選擇。如果userBrands在過濾器中找到品牌,則回傳 false,否則回傳 true。
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);
uj5u.com熱心網友回復:
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)
uj5u.com熱心網友回復:
如果您正在考慮過濾 allBrands 陣列,使其不包含用戶已經選擇的品牌。您可以嘗試制作 2 個 for 回圈并將一個嵌套在另一個中,然后回圈遍歷 allBrands 陣列以檢查它是否包含用戶已選擇的品牌。例子:
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);
}
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/462168.html
標籤:javascript
