Utilizing the Map Function for Monitoring Multiple Items

I need to loop through an array of objects to determine if specific criteria are met. Let's consider the structure of my array:

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: [{}],
  },
]

Currently, I have a checkMethodChosen function that uses the following logic:

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,
    })
  }

This function updates the state based on whether 'delivery_method' is set to 'pickup' with a selected pickup_day or if it's 'car' or 'bike'. It works well when there's only one object in the array but has issues with multiple objects.

The desired functionality is for this.state.deliveryChosen to be true only if 'delivery_method' is chosen in every object. If any object lacks this selection, then this.state.deliveryChosen should be false.

Appreciate your help!

Answer №1

If you're searching for a solution, the function that may be of use to you is every(). It will provide a true result if the callback function returns true for every element in an array.

To illustrate, here's a condensed version that simply gives back the boolean value:

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) {
    // Returns true if each item in arr meets the specified conditions:
    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))

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Deactivate the submission button when there are no search results in typeahead.js

How can I disable the submit button if there are no search results found? The form should not be submitted in this scenario. I am currently using typeahead.js for my code. $('.typeahead').typeahead(null, { name: 'suburb', disp ...

Issue with ion-content on Ionic app not scrolling down when keyboard is displayed on an Android device

Currently, I am facing an issue with a basic view that contains a login form. When the keyboard pops up on Android devices, the content does not scroll up to ensure it remains visible above the keyboard. I have diligently followed the Keyboard instruction ...

Using Vue.js: Execute a function with a delay, but start the delay over if there is any user input

Imagine a scenario where I have a form that is connected to an API and displays information based on user input. Whenever the user makes changes, such as adjusting the number of results per page, the component should react dynamically by loading new data. ...

Establishing a secondary Node.js service for local communication with Parse Server

My current project involves using Node.js + Parse Server for an application. I have been utilizing the Parse SDK from the client side, but there are still many changes and refactors that need to be made. One issue I am facing is that certain logic should b ...

Trouble arises with Javascript object destructuring when used with this.props in React

Just recently I discovered object destructuring with a basic object, which worked perfectly. However, when attempting to apply it in React on this.props, all my variables are returning as undefined. I'm unsure of what mistake I might be making here. A ...

I'm experiencing an issue with my dropdownlist not triggering the onchange event in AngularJS

I am a beginner in the world of AngularJS and I am trying to extract the values OnChange from a dropdown list. Here is the code that I have experimented with: <div> <select ng-controller="UserSelection as User" ng-model="User.UserSelected" n ...

Using Bootstrap CSS and JavaScript specifically for carousel functionality

Custom Styles and Scripts for Bootstrap Carousel Using Carousel with Controls https://getbootstrap.com/docs/4.0/components/carousel/ <div id="carouselExampleControls" class="carousel slide" data-ride="carousel"> <div class="carousel-inner ...

Iterate through intricate array structures using the most efficient approach and minimal complexity

I have a scenario where I need to call an API that returns data in the following format: [{ Id: string, Value: string, Value2: [{Id: string, Value3: string}] , { Id: string, Value: string, Value2 ...

Capture the response from an AJAX request and store it in a JavaScript variable

I've been struggling to find a solution for this issue for quite some time now without any success. Here's what I'm trying to accomplish: I need to retrieve an array from my PHP file so that I can utilize it in my JavaScript code. Example. ...

Is there a way to send a JSON object and a file to an ASP.NET server using the fetch method?

I'm facing a challenge here, as I attempt to send a json object from my indexedDb along with an IFormFile object to the server at the same time. The method that handles this scenario is structured like so: [HttpPost] public async Task<IActionR ...

Creating 3D extrusions with Three.js by specifying depth and a direction vector

My goal is to extrude a shape and generate an ExtrudeGeometry, but I need the ability to control the direction of the extrusion. Specifically, I have a direction specified in a Vector3. The shape is initially drawn on the x-y plane, with the default extru ...

Navigating the NestJS @Get() Decorator: A Comprehensive Guide

The code snippet above demonstrates the functionality of accessing two different functions using URLs like http://localhost:3000/vehicle/availableVehicles and http://localhost:3000/vehicle/1. Both functions work properly in this setup. @Controller(&apo ...

Searching for and replacing text that spans across multiple nodes in HTML can be accomplished using C# programming language

Here is the HTML code to consider. The term 'response' was modified to 'reason', by removing 'sp' (<del> tag) and adding 'as' (<ins> tag), while also removing 'se' (<del> tag). <div &g ...

Display a div with a link button when hovering over an image

Currently, I'm attempting to display a link button within a div that will redirect the user to a specified link upon clicking. Unfortunately, my current implementation is not functioning as expected. I have provided the code below for reference - plea ...

Include a Vue component within another Vue component in a Laravel application using VueJs

I've recently integrated Vue.js into my Laravel project and encountered an issue when trying to call a component within another component. After running the command npm run dev, I received a webpack error. Here is the code snippet from my parent comp ...

Disabling the scaling feature in IE11's WebBrowser control: A step-by

After investing 48 hours into resolving this particular issue, I am reaching out to the knowledgeable StackoverFlowers community for assistance. My current project involves developing an application for large 27-inch multi-touch screens using C# 4.5. Withi ...

Is there a way to retrieve the content of an element using JavaScript?

I'm currently working on retrieving the value and content of an option element. I've managed to obtain the value using this.value as shown in the code snippet below: <select name='name' id='name' onchange='someFunctio ...

The issue arises when the export function is triggered within the getStaticPaths() method, preventing the top-level

For my Next.js SSG (static site generation) app, I decided to optimize the database connection process by exporting a global promise from one file and then utilizing it in another file called controllers.js. This file houses multiple functions that directl ...

"Utilizing Vue.js to dynamically fill input fields based on the selection of an element

As I am still new to learning Vue.js, I may not be using the correct terminology here. My current project involves a basic Vue application where I have implemented a simple search box functionality. The search box triggers an event (v-on:blur) when text i ...

What is the best way to select or deselect all asp.net checkboxes with just one checkbox event?

I am looking for a way to control the checkboxes on my webpage using a checkbox named Select All, allowing me to check or uncheck all checkboxes within individual div sections. Since my checkboxes are asp.net controls with runat=server, I am unsure how to ...