Home > OS >  How to take only specific indexes and map to another indexes?
How to take only specific indexes and map to another indexes?

Time:01-20

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.

CodePudding user response:

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

CodePudding user response:

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);
  • Related