根据id合并2个数组,并优先将最新过滤的放在最上面

问题描述 投票:0回答: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(),
  ];
}

在此代码中也不适用于每个过滤器数组,这里数组中的每个产品都来自服务器 menuFilteredProducts 是从菜单获取数组的功能, categoryFilteredProducts 是从侧边栏选择中获取的数组的功能。

我需要react.js或next.js脚本的有效解决方案

reactjs javascript-objects next.js13 array-merge
1个回答
0
投票

您可以按照以下步骤操作:

  1. 合并两个数组

  2. 使用地图确保每个产品根据其 ID 都是唯一的。

  3. 根据所需标准对结果数组进行排序(最新产品优先)。

    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);
    
© www.soinside.com 2019 - 2024. All rights reserved.