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.
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]);
}