const menuFilteredProducts = getMenuWiseProduct(products);
const categoryFilteredProducts = getCategoryWiseProduct(products);
let mergedProducts = [];
const prioritizeCategory = true;
if (prioritizeCategory) {
mergedProducts = [
...new Map(
[...categoryFilteredProducts, ...menuFilteredProducts].map((item) => [
item.id,
item,
])
).values(),
];
} else {
mergedProducts = [
...new Map(
[...menuFilteredProducts, ...categoryFilteredProducts].map((item) => [
item.id,
item,
])
).values(),
];
}
在此代码中也不适用于每个过滤器数组,这里数组中的每个产品都来自服务器 menuFilteredProducts 是从菜单获取数组的功能, categoryFilteredProducts 是从侧边栏选择中获取的数组的功能。
我需要react.js或next.js脚本的有效解决方案
您可以按照以下步骤操作:
合并两个数组
使用地图确保每个产品根据其 ID 都是唯一的。
根据所需标准对结果数组进行排序(最新产品优先)。
const menuFilteredProducts = getMenuWiseProduct(products);
const categoryFilteredProducts = getCategoryWiseProduct(products);
// Function to merge and prioritize products
const mergeAndPrioritizeProducts = (menuProducts, categoryProducts) => {
// Combine both arrays
const combinedProductsArray = [...menuProducts, ...categoryProducts];
// Create a Map to filter out duplicates based on id
const productMap = new Map();
combinedProductsArray.forEach((product) => {
// If the product is not already in the map, or if it is, we want to keep
the latest one
if (!productMap.has(product.id) || (productMap.get(product.id).updatedAt <
product.updatedAt)) {
productMap.set(product.id, product);
}
});
// Convert the Map back to an array
const filteredUniqueProducts = Array.from(productMap.values());
// Sort the products based on the latest updatedAt date (or any other
criteria)
filteredUniqueProducts.sort((a, b) => new Date(b.updatedAt) - new
Date(a.updatedAt));
return filteredUniqueProducts;
};
// Call the function to get the merged and prioritized products
const mergedProducts = mergeAndPrioritizeProducts(menuFilteredProducts,
categoryFilteredProducts);