What is the method for selecting specific indices and then matching them to different indices?

There is a need to execute an API call with specific parameters.

Here is an example:

const apiFunc = (someId, anotherId) => apiCall(someId, anotherId)

However, when the data is stored in an array named someArr, it appears like this:

[1, 'someId', 2, 'anotherId', 3, 'anotherId', 4, 'someId']

The goal is to utilize values in the function apiCall() based on certain conditions. For instance, if 1 (same as 4) is followed by 'someId', then use it, and if 2 (same as 3) is followed by 'anotherId', then use it.

Could you please suggest how to properly structure this to achieve the desired outcome?

Thank you.

I have attempted using .includes() method but it hasn't been very successful.

Answer №1

To efficiently retrieve values before "someId" and "anotherId", you can utilize the `filter` method in JavaScript. Extract the values preceding each identifier and then pair them for API calls:

// Example to demonstrate
const apiCall = (someId, anotherId) => console.log(someId, anotherId);

const arr = [1, 'someId', 2, 'anotherId', 3, 'anotherId', 4, 'someId'];

// Retrieve all values before "someId"
const someIdValues = arr.filter((val, i) => arr[i+1] === "someId");
// Retrieve all values before "anotherId"
const anotherIdValues = arr.filter((val, i) => arr[i+1] === "anotherId");

// Pair and make API calls
for (let i = 0; i < someIdValues.length; i++) {
    apiCall(someIdValues[i], anotherIdValues[i]);
}

Answer №2

To implement a basic function, consider the following approach:

const findNextId = (arr, num): string | null => {
  const index = arr.indexOf(num);

  if (index === -1 || index === arr.length - 1) {
    return null;
  }

  return arr[index + 1];
};

You can then apply it as follows:

const nextId1 = findNextId(someArray, 1);  // 'someIdentifier'
const nextId2 = findNextId(someArray, 3);  // 'anotherIdentifier'

executeApiCall(nextId1, nextId2);

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

Nestjs Roles Decorator: Unusual behavior in extracting user from payload information

I have been working on implementing my Roles Decorator in Nestjs and it has been going well. However, I encountered an issue when trying to compare the user data from the jwt-token payload to the required role. Strangely, I found that I can only access the ...

extracting a characteristic from one entity and transferring it to another entity

Hey there, I have a tricky problem to solve. I am trying to extract a value from an array that's inside an object. $scope.document=[] $scope.accounts=[{name:"123"},{name:"124"},{name:"125"}] My goal is to take the first array element and append it ...

Missing 'id' property in object {`id`} when utilizing GraphQL with Typescript

As a newcomer to coding and Typescript, I apologize for my limited knowledge. I am currently facing an issue where my application is unable to communicate with my API due to an error caused by the primary id key having a "?" symbol, like so: export interfa ...

Trigger a pop up using AJAX when successful

There is a button that, when clicked, triggers a pop up dialog box with the code below: <div class="button-wrap"><button data-dialog="somedialog" class="trigger">Open Dialog</button></div> The script responsible for activating the ...

No data found in the subrow of the datasource after the filter has been

I am working with a material table that has expandable rows. Inside these expanded rows, there is another table with the same columns as the main table. Additionally, I have implemented filters in a form so that when the filter values change, I can update ...

Adonis.js Creating a RESTFUL API Solution

I recently embarked on a new project using the adonisjs framework. I had the option to utilize expressjs, but I was drawn to adonisjs due to its structured nature, especially reminiscent of Laravel. My current challenge revolves around building a RESTful ...

jQuery's callback handling often reverses the statement I just made

My current project involves using AJAX with jQuery to send a get request. Once the request is successful, I insert the response into a specific div: $.get("content.php", function(result) { $('#content').html(result); The content I'm fetc ...

Can you demonstrate how to display the chosen toggle button within Angular 4 alongside the remaining options?

I have created a custom toggle button component in Angular that I can reuse in different parts of my application. However, I am facing an issue that I need help resolving. I want to display only the selected toggle button and hide the others. When I click ...

Tips for attaching an event listener to a div element that is accessed by reference in a React and TypeScript environment

I am attempting to attach an event listener to the div element using a ref. In my code, I have added a ref called div_ref to the Wrapper div and accessed that div_ref in the enableDragEventListeners method to add event listeners to it on component mount. ...

Issues with implementing Bootstrap tabs in Vue application

Currently, I am in the process of developing an application using vue, vue-router, and bootstrap. My goal is to integrate tags in bootstrap as shown below: <ul class="nav nav-tabs" role="tablist"> <li class="nav-item"> <a class="nav-l ...

Re-sending keyup event for DATE input in JavaScript

Is there a way to redirect the keyup KeyboardEvent from one native date input element to another in real time, similar to typing in two date inputs simultaneously? I experimented with this code using a text input, and it worked perfectly. However, when I ...

What is the method for retrieving a JSON data array using PHP/Laravel?

Currently, I am working on developing an API using Laravel and my task involves retrieving data from a JSON file located at a specific URL. Below is the code snippet I have written for this purpose: public function index(){ $json_file=file_get_contents ...

The addRows() method in Google charts seems to be stubborn when it comes to accepting arrays as input

Attempting to create a line chart, but facing an error with Google Charts when trying to add a row of data: Error: Every row given must be either null or an array. @ ...corechart.I.js:162 Below are sample columns I attempted to use. Columns are set up ...

Summing up the elements of an array and iterating over the entire array in MATLAB

I am working with a matrix A that is 3780x30974 in size and consists of only 0s and 1s. My goal is to calculate the sum of fixed windows of length 21 (180 blocks) within this matrix. The expected output should be a vector of size 180x30974. For each colum ...

extract non-alphanumeric characters from an array of strings using javascript

I am trying to loop over an array of strings in JavaScript and remove special characters from elements that contain them. I have been successful in achieving this with individual strings, but I am facing some challenges when working with arrays of string ...

Accessing object fields in real-time

Currently restructuring Vuex, and facing a common action: deleteFromList ({commit}, {list = '', type = '', listPlural = '', data = {}}) { db.rel.find(list, data).then(doc => { return db.rel.del(list, doc.rooms[0]) ...

Using a static class reference as a parameter in a generic type leads to a error

Before I submit a ticket on github, I want to double-check that I'm not making any mistakes. The issue should be clear enough: class A {} class B { static A = A; } function foo<T>(arg: T) {} // this is valid const b = new B.A; // "B" only ...

What is the best way to replicate certain key-value pairs in an array of objects?

I am working with an array of objects. resources=[{name:'x', title:'xx',..},{name:'y',title:'yy',..}..] To populate my HTML tooltip, I am pushing all the titles from the resources array to a new array. dialogOkCli ...

Expand the font manually

Is there a way to define a type that represents the widened version of another type? Consider the following scenario: function times<A extends number, B extends number>(a: A, b: B): A & B; The intention behind this times function is to preserv ...

incorporating the same model into the scene multiple times

Currently, I am loading a single model multiple times using the following code: var loader = new THREE.JSONLoader(); loader.load(model, load_func); The function load_func is responsible for creating a mesh and adding it to the scene: var mesh = new THRE ...