Categories
JavaScript Answers

How to use promise in forEach loop of array to populate an object with JavaScript?

To use promise in forEach loop of array to populate an object with JavaScript, we use Promise.all with an array of promises.

For instance, we write

const promises = array.map(async (element) => {
  const data = await developer.getResources(element);
  name = data.items[0];
  const response = await developer.getResourceContent(element, file);
  fileContent = atob(response.content);
  files.push({
    fileName,
    fileType,
    content,
  });
});

await Promise.all(promises);

to call array.map with an async function which returns a promise.

Therefore, promises is an array of promises.

And we call Promise.all with promises to return a promise that resolves when all the promises are resolved.

The promises are run in parallel.

Categories
JavaScript Answers

How to append an array to form data in JavaScript?

To append an array to form data in JavaScript, we call the append method.

For instance, we write

formData.append("tags", JSON.stringify(tags));

to call formData.append with the key and value of the entry.

The value is an array converted to a JSON string with JSON.stringify.

Categories
JavaScript Answers

How to sum values from an array of key-value pairs in JavaScript?

To sum values from an array of key-value pairs in JavaScript, we use the map and reduce methods.

For instance, we write

const myData = [
  ["2013-01-22", 0],
  ["2013-01-29", 0],
  ["2013-02-05", 0],
  ["2013-02-12", 0],
  ["2013-02-19", 0],
  ["2013-02-26", 0],
  ["2013-03-05", 0],
  ["2013-03-12", 0],
  ["2013-03-19", 0],
  ["2013-03-26", 0],
  ["2013-04-02", 21],
  ["2013-04-09", 2],
];
const sum = myData.map(([, v]) => v).reduce((sum, current) => sum + current, 0);

to call myData.map with a callback that gets the 2nd value from each nested array.

Then we call reduce to return the sum of sum and current and set the initial sum to 0.

Categories
JavaScript Answers

How to create a fixed length array in JavaScript?

To create a fixed length array in JavaScript, we call the Object.seal method.

For instance, we write

const a = new Array(100);
a.fill(undefined);
Object.seal(a);

to create array a with length 100.

Then we call fill with undefined to fill all empty slots with undefined.

We need to fill the empty slots since they can’t be changed after seal is called.

Then we call Object.seal to seal array a to keep its length from changing.

Categories
JavaScript Answers

How to sum two arrays in single iteration with JavaScript?

To sum two arrays in single iteration with JavaScript, we use the map method.

For instance, we write

const array1 = [1, 2, 3, 4];
const array2 = [5, 6, 7, 8];

const sum = array1.map((num, idx) => {
  return num + array2[idx];
});

to call array1.map with a callback that returns the sum of num and item in array2 at the same idx index.

The array with the sums is returned.