taway0282
taway0282

Reputation: 197

Reactjs - Can't get value from array, undefined

I am trying to compare the values from 2 state arrays, but when I look at the value of otherItems[i] I get undefined. For clarification, Items is an array of Objects with many data points, why I'm calling it with .name, while otherItems is just an array of the names. If I call just this.state.otherItems then I get the full array contents.

this.state = {
  Items: [],
  otherItems: [],
  ...
}
...
function = () => {
  var total = this.state.total;
  var i;
  for(i = 0; i < this.state.Items.length; i++) {
    console.log(this.state.otherItems[i]);
    if(this.state.Items[i].name === this.state.otherItems[i]) {
      total += parseFloat(this.state.Items[i].price)
    }
  }
  this.setState({Total: total})
}

What I would like to happen is the items from the two arrays compare, and the price of the item is added to the total sum if and only if the item i from Items exists in otherItems.

Upvotes: 1

Views: 522

Answers (1)

Tholle
Tholle

Reputation: 112777

You are using a loop variable i and using that to index both arrays, so you are only comparing elements with the same index between the two arrays, and the two arrays might differ in length.

You could instead use includes to check if the name of an element in Items is present in the otherItems array.

getTotal() {
  this.setState(({ total = 0, Items, otherItems }) => {
    Items.forEach(item => {
      if (this.state.otherItems.includes(item.name)) {
        total += parseFloat(item.price);
      }
    });

    return { otherTotal: total };
  });
}

Upvotes: 2

Related Questions