Search code examples
javascriptreactjsecmascript-6react-hooksecmascript-2016

Set ID's If Found in Array in React


I have a list of array called productsList and I also have an array called chosenProducts. I want to see in the setProducts if ids of chosenProducts is found in productsList

Expected Output

[
    "AAA"
]

productsList

[
    {
        "id": "AAA",
    },
    {
        "id": "BBB",
    },
]

chosenProducts

[
    "AAA",
    "DDD"
]

code

setProducts([])

Solution

  • You can map and filter those that items from productList that are in chosenProducts using Array.prototype.reduce and Array.prototype.includes

    var productList = [
        {
            "id": "AAA",
        },
        {
            "id": "BBB",
        },
    ]
    
    var chosenProducts = [
        "AAA",
        "DDD"
    ]
    
    var products = productList.reduce((acc, product) => {
      if(chosenProducts.includes(product.id)) {
         acc.push(product.id);
      }
     return acc;
    }, []);
    console.log(products);