Identify the following map based on the sequence in the mapsOrder array

I have two arrays, mapsOrder and mapsData, containing objects:

let mapsOrder = [1,2,1,3];
let mapData = [
  {
    id: 1,
    gates: [
      {
        toId: 2,
        coords: {
          x: 2,
          y: 42
        }
      },
      {
        toId: 3,
        coords: {
          x: 9,
          y: 4
        }
      }
    ]
  },
  {
    id: 2,
    gates: [
      {
        toId: 1,
        coords: {
          x: 6,
          y: 5
        }
      }
    ]
  },
  {
    id: 3,
    gates: [
      {
        toId: 1,
        coords: {
          x: 2,
          y: 1
        }
      }
    ]
  }
]

The goal is to loop through the mapsOrder array where its values correspond to ids in mapData, and assign gates to the next map.

During each iteration:

  • When index is 1, current map is 1, next map is 2, and gates to next are coords: { x: 2, y: 42 }
  • When index is 2, current map is 2, next map is 1, and gates to next are coords: { x: 6, y: 5 }
  • When index is 3, current map is 1, next map is 3, and gates to next are coords: { x: 9, y: 4 }
  • When index is 4, current map is 3, next map is 1, and gates to next are coords: { x: 2, y: 1 }

For the last iteration, the next map will be the first one in the mapsOrder array. I attempted to achieve this by determining the id of the next map using the following code snippet:

for(let i = 0; i < mapsOrder.length; i++) {
  let nextMap;
  let currentMapId = mapData[mapsOrder[i] - 1].id;
  if(i === mapsOrder.length - 1) {
    nextMap = mapData[0].id   
  } else {
    nextMap = mapData[mapsOrder[i]].id;    
  }

  console.log('Current map is: ', currentMapId, 'and the next map id is:', nextMap)
  console.log('break-----')

}

However, this code returns incorrect IDs. You can view a live demo here.

Answer №1

If you are not concerned about the original array, you can simply utilize `shift` to retrieve the next gate (since `shift` removes the gate from the array, making the next gate available when the object is encountered again). Use `find` to search for the object in the array:

let result = mapsOrder.map(id =>
    mapData.find(o => o.id == id).gates.shift().coords
);

It might be wise to verify if `find` actually locates something and if the gates array contains elements before applying `shift`. Here is a more cautious approach:

let result = mapsOrder.map(id => {
    let obj = mapData.find(o => o.id == id);
    if(obj && obj.gates.length) {                  // if an object with the specified id is found and it has gates
        return obj.gates.shift().coords;           // retrieve the coordinates of the first gate while removing it from the array
    }                                              // alternatively, handle the absence of gates
});

No modifications:

Rather than utilizing `shift` as shown previously, we will employ an object to monitor the gate index from the `gates` array:

let nextGateIndex = Object.create(null);                             // creating a prototypeless object to track the next gate index for each object
let result = mapsOrder.map(id => {
    let obj = mapData.find(o => o.id == id);
    let index;
    if(nextGateIndex[id] == undefined) {
        index = 0;
    } else {
        index = nextGateIndex[id] + 1;
    }
    nextGateIndex[id] = index;
    if(obj && index < obj.gates.length) {
        return obj.gates[index].coords;
    }                                                                // handle error or alternative path
});

Answer №2

If you follow the description, your loop should look like this. It seems that you want to utilize id and toId, but in the context of array indexes. Consider replacing arrays with objects for a better approach.

Check out the demo here

for(let i = 0; i < mapsOrder.length; i++) {
  let nextMap;
  let currentMapId = mapsOrder[i];
  if(i === mapsOrder.length - 1) {
    nextMapId = mapsOrder[0]   
  } else {
    nextMapId = mapsOrder[i + 1];    
  }
  let filteredMapData = mapData.filter(f => f.id == currentMapId);
  let filteredGates = filteredMapData.length > 0 ? filteredMapData[0].gates.filter(f => f.toId == nextMapId) : [];

  console.log('Current map is: ', currentMapId, 'and the next map id is:', nextMapId, 'gates:', filteredGates.length == 0 ? "no gates": filteredGates[0].coords)
  console.log('break----')

}

Answer №3

If you're working with JavaScript arrays, I highly recommend using the filter() function. It's incredibly efficient and will create a new array containing elements that meet specific criteria (such as objects with a desired id).

for (let i = 0; i < mapsOrder.length; i++) {
    console.log(mapData.filter(mapDataItem => mapDataItem.id === mapsOrder[i]))
}

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

Why is my snapshot returning null, even though there are values in the Firebase Database?

I am currently facing an issue in my code related to the snapshot. Specifically, I am trying to retrieve the value of quantity from my Firebase Database. Here's a snapshot of my database: https://i.sstatic.net/qN6m4.jpg and https://i.sstatic.net/Gw ...

What is the best way to transform array values that are already in array form?

Here's my current method, but I'm wondering if there is a better way to achieve the same result using functions. Your suggestions are greatly appreciated. I have an array called $items with the following output: array (size=2) 0 => ar ...

Filtering complexity with array and object containing an array element

I am working with two arrays let badContents = ["b1", "b2"] let things: [Thing] = ... Each Thing object in the array has its own set of contents, as shown below print(things[0].contents) // ["g1", "b1", "b2"] My goal is to filter out elements from the ...

Ensure that the function is executed following the refresh of the div's content

There's a div with some content in it. Initially, this function works well when the page loads. However, if I use JavaScript to update the div with new content, this function stops working. I'm stuck and not sure how to fix this issue. Can anyon ...

In a JavaScript array of objects, the Vuetify select :items feature allows you to assign an id and name to each object. When a name is selected, the corresponding id is automatically

I am currently working with an array of objects that contain both an id and a name property: Teams [ { id: 1, name: 'team1' }, { id:2, name: 'team2' } ] Is there a way to dynamically pass the names as items in a vuetify selec ...

Transform list of objects into a one-dimensional array

My formData serializeArray function returns an array of objects, such as: [ 0 : {name: 'animal_monkey', value: 'banana'} 1 : {name: 'animal_horse', value: 'radishes'} 2 : {name: 'fruit_ba ...

Issue with host header detected in MERN stack configuration

"proxy": "https://mango-artist-rmdnr.pwskills.app:5000", While attempting to establish a connection between my frontend and backend, I encountered an issue with an invalid host header. The backend is operating on port 5000, and the fr ...

Retrieve information filtered based on the query parameter

Utilizing react hooks for dynamic data rendering, I am focusing on two main tasks: a. Extracting URL parameters from the component's history props. b. Retrieving state data from the component's history props, which provides an array of objects ...

Steps to access the most recent eventName (determined by date)

I am working with two arrays var events=["DELIVERED", "OUT TO DELEVERY", "REACHED WAREHOUSE", "DEPARTED"]; var eventDetails= [{ "source" : "application" "DateTime": "2016-05-12 11:20:00", "eventName" : "DELIVERED" }, { "source" : "application" "DateTime" ...

Retrieving outcome of Solidity contract function using web3-1.0.0-beta.27

I am using web3 1.0.0-beta.27 and the pragma solidity is set to ^0.4.2. contract Charity{ function ping() public constant returns (uint) { return 200; } } Currently, I am compiling and calling it in typescript with: import * as fs ...

Neglecting a value when parsing through an array

Currently, I am in the process of analyzing an array. To do so, I am using a struct to store both the position and value of each element within the array. My goal is to identify the three minimum values present in the array while disregarding a specific va ...

What is the best way to arrange an array of identical objects based on a specific sub property?

Here's an array of items to work with: myArray = [ { someDate: "2018-01-11T00:00:00", name: "John Smith", level: 5000 }, { someDate: "2017-12-18T00:00:00", name: "Jane Doe", level: 1000 }, { ...

The feature for sending posts in Angular.js appears to be malfunctioning

I have developed a rest-API for adding todos in a MongoDB database. When I use Postman with the setup below, I can successfully save instances: http://localhost:3000/api/addtodo x-www-form-urlencoded with values text="Test", completed: "false". However, ...

Ensuring a correct dismount of a React component

Apologies for the lack of specificity in the title of this inquiry. Upon executing the code snippet below, I encountered the ensuing warning: Warning: setState(...): Can only update a mounted or mounting component. This typically indicates that you call ...

Image Blob increases over 50 times its original size when uploaded

I'm completely baffled by the situation unfolding here. Using Preprocess.js, I am resizing/compressing an image on the front-end. During the processfile() function on the image.onload (line 32), I convert the toDataURL() string to a Blob, in order to ...

Issue Alert: React - Material-UI version 6 does not support renderInput Property in DesktopDatePicker

Exploring the integration of React with Material UI Version 6 Library, I am looking to personalize the appearance of the rendered Input. In the previous version, Version 5, there was a property called "inputProp" for DateTimePicker. However, this feature ...

Is the widgetURL being overridden within the Foreach loop?

Presented in my iOS 14 medium-size widget are three rows structured as follows: row 1 ------- row 2 ------- row 3 ------- Below is the layout of my view: VStack { ForEach(records, id: \.id) { item in ZStack { // various vi ...

Transforming a Vue.js sample to incorporate ajax requests

For my latest project, I am incorporating Vue.js. One part of the project requires rendering a tree view that is stored in a database. I have taken inspiration from the Vue.js tree view example and have successfully retrieved the data from my server in the ...

Locating the ID of the child div that was clicked within a parent div element

My HTML code snippet looks like: <div id="edit" ng-click="editFunction($event)"> <span id="1"> click1 </span> <span id="2"> click2 </span> <span id="3"> click3 </span> <span id="4"> ...

Toggling checkboxes using Angular framework

Within my form, there is a table with checkboxes in each column. The table consists of 3 <tr> elements, and each <tr> uses ng-repeate to call the webservice and display clone data (in JSON format). Upon clicking a checkbox, I create a JavaScrip ...