0

I have to call an endpoint multiple times and get the responses aggregated to a single array. Below is the response from the endpoint;

{
   items: [
      {key1: value},
      {key2: value}
   ]
}

Below is the code to call the endpoint multiple times;

const chunkedArray = getChunkedArray(largeArray);
const result = await Promise.all(
   chunkedArray.map(async (items) => {
      const response = await ....get(`http:/url/${items}`);
      return response.items;
   });
);

For the result I'm getting below;

[
   [
      {key1: value},
      {key2: value}
   ],
   [
      {key3: value},
      {key4: value}
   ]
]

What I want is an aggregated array like below;

[
   {key1: value},
   {key2: value},
   {key3: value},
   {key4: value}
]

What is the optimum way of doing that?

1
  • how you are appending the chunks to the final array? Commented May 21, 2021 at 12:34

1 Answer 1

1

Try using Array.prototype.flat();

let arr1 = [
   [
      {key1: value},
      {key2: value}
   ],
   [
      {key3: value},
      {key4: value}
   ]
]

let arr2 = arr1.flat(); 
/* [
      {key1: value},
      {key2: value},
      {key3: value},
      {key4: value}
   ] */


If you want to do it without flat you can use reduce too :

let promises = Promise.all(
   chunkedArray.map(async (items) => {
      const response = await ....get(`http:/url/${items}`);
      return response.items;
   });
);

const result =promises.reduce((cum,x) => {
let newArr = await x;
return [...cum,...newArr ];
},[]);

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.