Categories
JavaScript Answers

How to declare an array in JavaScript?

To declare an array in JavaScript, we use array literals.

For instance, we write

const x = [];
const y = [10];

const z = [];
z[2] = 12;

to declare array x which is an empty array.

We declare y which is an array with 10 in it.

And we declare array z as an empty array and then set 12 as the 3rd element in z.

Categories
JavaScript Answers

How to count the number of times a same value appears in a JavaScript array?

To count the number of times a same value appears in a JavaScript array, we call the filter method.

For instance, we write

const getOccurrence = (array, value) => {
  return array.filter((v) => v === value).length;
};

console.log(getOccurrence(arr, 1));

to call array.filter with a callback that checks if v in array equals to value.

An array of values in array that equals to value is returned.

Then we get the count using the length property.

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.