Dres
Dres

Reputation: 1499

Checking Multiple Items with a Map Function

I want to check each object in an array to see if certain things exist. So let's say my array looks like this:

const arrayOfItems = [
  {
    delivery_method: {
      delivery_method: 'car',
      delivery_rate: 1,
      pickup_day: 'none',
    },
    total_cost: 5,
    items: [{}],
  },
  {
    delivery_method: {
      delivery_method: 'pickup',
      pickup_day: 'T',
      delivery_rate: 0,
    },
    total_cost: 5,
    items: [{}],
  },
]

And now I have a check methods function that looks like this:

async checkMethodChosen() {
    let check = await arrayOfItems.map((item) => {
      if (
        (item.delivery_method.delivery_method === 'pickup'
          && item.delivery_method.pickup_day !== 'none')
        || item.delivery_method.delivery_method === 'car'
        || item.delivery_method.delivery_method === 'bike'
      ) {
        return false
      }
      return true
    })
    let deliveryChosen = check.includes(false)

    this.setState({
      deliveryChosen,
    })
  }

The function sets the state with true or false if delivery_method is set to 'pickup' and the pickup_day is selected OR if delivery_method === 'car' or 'bike' . This works fine if there's only one object in the array. It's not working if there are multiple objects.

What I want to happen is if there are multiple objects, then this.state.deliveryChosen should only be true if delivery_method has been selected in each object. If it hasn't been selected for one object, then this.state.deliveryChosen should be false.

Thanks!

Upvotes: 0

Views: 264

Answers (1)

Mark
Mark

Reputation: 92440

The function you are looking for is every() it will return true if the callback returns true for every item in an array.

For example here's a simplified version that just returns the boolean:

const arrayOfItems = [{delivery_method: {delivery_method: 'car',delivery_rate: 1,pickup_day: 'none',},total_cost: 5,items: [{}],},{delivery_method: {delivery_method: 'pickup',pickup_day: 'T',delivery_rate: 0,},total_cost: 5,items: [{}],},]

function checkMethodChosen(arr) {
    // will return true if every item of arr meets the following condition:
    return arr.every((item) => 
       (item.delivery_method.delivery_method === 'pickup' && item.delivery_method.pickup_day !== 'none')
       || item.delivery_method.delivery_method === 'car'
       || item.delivery_method.delivery_method === 'bike'
    ) 
}
console.log(checkMethodChosen(arrayOfItems))

Upvotes: 2

Related Questions