Home > Enterprise >  react forEach and at hook not working as expected
react forEach and at hook not working as expected

Time:12-02

I have a forEach statement that is comparing the values in two arrays. I break down the products object into different arrays so I know for sure what I am comparing. When I have one value in the basket array it works as expected. when there are two or more values in the basket array the prices are set to the first index of productPriceArray.

My goal is to compare two arrays and if they are the same, push the price at the index that I am testing to a new array. once I have the new array I reduce it to give me the full price of all the prices in the that array.

thanks for any help!

const [basket, addToBasket]= useState([]);
const productPriceArray = products.map((items) => (items.price));
const productIDArray = products.map((items) => (items.id));

  const itemsInBasketEqualToProducts = [];
  basket.forEach((element) => {
    if (element = productIDArray) {
         itemsInBasketEqualToProducts.push(productPriceArray.at(basket-1))
     
    }
  });

  const sum = itemsInBasketEqualToProducts.reduce(
    (accumulator, currentValue) => accumulator   currentValue,
    0
  );

CodePudding user response:

Looks like the problem is in your if statement and its contents. First, = is for assignment and == is for comparison, so you have accidentally assigned the productIdArray to the variable element in that statement.

Moveover, productIdArray is an array so it will never be equal to anything except itself. It looks like what you want to do is see if element is in the array, for which you can use the array .includes method.

Putting that together, you might rewrite that like so:

if (productIdArray.includes(element)) {

Next, if that statement above is true, you want to put the price of the current item into your itemsInBasketEqualToProducts array. Since the price should be at the same index as the id in their respective arrays, you can use indexOf to locate the correct index to pull the price from:

const itemPrice = productPriceArray[productIdArray.indexOf(element)]
itemsInBasketEqualToProducts.push(itemPrice)

Putting all that together, your final snippet might look like:

const [basket, addToBasket] = useState([]);
const productPriceArray = products.map((items) => (items.price));
const productIDArray = products.map((items) => (items.id));

const itemsInBasketEqualToProducts = [];
basket.forEach((element) => {
  if (productIDArray.includes(element)) {
    const itemPrice = productPriceArray[productIdArray.indexOf(element)]
    itemsInBasketEqualToProducts.push(itemPrice)
  }
});

const sum = itemsInBasketEqualToProducts.reduce(
  (accumulator, currentValue) => accumulator   currentValue,
  0
);

  • Related