Reputation: 1
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(),
];
}
In this code also not work on every filter array here every products in array comes from server menuFilteredProducts is feature of array get from menu, categoryFilteredProducts is feature of array get from sidebar selection.
i need effective solution on react.js or next.js script
Upvotes: 0
Views: 24
Reputation: 11
You can follow below steps :
Combine both arrays
Use a Map to ensure that each product is unique based on its id.
Sort the resulting array based on the desired criteria (the latest products first).
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);
Upvotes: 0