0

I need to make an api call with particular parameter.

See example below:

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

However in an array called someArr I get something like [1, 'someId', 2, 'anotherId', 3, 'anotherId', 4, 'someId']

I need to use in apiCall() if for example 1 (same as 4) if 'someId' is next to it, and 2 (same as 3) if 'anotherId' is next to it.

How can I properly format this please to achieve desired result?

Thanks

I have tried using .includes() but without much success.

  • [Chunk the array into tuples](https://stackoverflow.com/q/8495687/1048572), create a `Map` from it, then `apiCall(map.get(1), map.get(3))`. – Bergi Jan 20 '23 at 11:45
  • Can you post an example please? @Bergi – Mister Mister Jan 20 '23 at 11:45
  • Your question is not clear. Can you be explicit which separate `apiCall` calls you want to make (with literal arguments provided) for a sample input array? – trincot Jan 20 '23 at 12:41

2 Answers2

1

You could use filter to extract all values that precede "someId", and another filter call to extract all values that precede "anotherId". Then pair them when you make the api calls:

// Mock 
const apiCall = (someId, anotherId) => console.log(someId, anotherId);

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

// Extract the "someId" values
const someId = arr.filter((val, i) => arr[i+1] == "someId");
// Extract the "otherId" values
const otherId = arr.filter((val, i) => arr[i+1] == "anotherId");
// Iterate the pairs of someId, otherId:
for (let i = 0; i < someId.length; i++) {
    apiCall(someId[i], otherId[i]);
}
trincot
  • 317,000
  • 35
  • 244
  • 286
0

You can create a simple function like this:

const getId = (array, number): string | null => {
  const index = array.indexOf(number);

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

  return array[index + 1];
};

and then use it like so:

const id1 = getId(someArr, 1);  // 'someId'
const id2 = getId(someArr, 3);  // 'anotherId'

apiCall(id1, id2);
Yuriy Yakym
  • 3,616
  • 17
  • 30