Categories
JavaScript Answers

How to compute the sum and average of elements in an array with JavaScript?

To compute the sum and average of elements in an array with JavaScript, we use the reduce method.

For instance, we write

const average = (arr) => arr.reduce((p, c) => p + c, 0) / arr.length;
const result = average([4, 4, 5, 6, 6]);
console.log(result);

to define the average function that calls arr.reduce to return the sum of the entries in arr.

And we divide the sum by arr.length array length to get the average.

Then we call average to return the average of the entries in [4, 4, 5, 6, 6].

Categories
JavaScript Answers

How to get a list of associative array keys with JavaScript?

To get a list of associative array keys with JavaScript, we call the Object.keys method.

For instance, we write

const dictionary = {
  cats: [1, 2, 37, 38, 40, 32, 33, 35, 39, 36],
  dogs: [4, 5, 6, 3, 2],
};

const keys = Object.keys(dictionary);
console.log(keys);

to call Object.keys with dictionary to return a list of key strings from the dictionary object.

Categories
JavaScript Answers

How to do map and filter an array at the same time with JavaScript?

To map and filter an array at the same time with JavaScript, we use the flatMap method.

For instance, we write

const names = options.flatMap((o) => (o.assigned ? [o.name] : []));

to call options.flatMap with a callback that checks if o.assigned is set.

If it is, then we array with o.name inside.

Otherwise, we return an empty array.

And we use flatMap to combine them into one flattened array.

Categories
JavaScript Answers

How to check if a string contains text from an array of substrings in JavaScript?

To check if a string contains text from an array of substrings in JavaScript, we can use the some and includes method.

For instance, we write

if (substrings.some((v) => str.includes(v))) {
  // ...
}

to call some on the substrings array with a callback that calls str.includes with the v entry being looped through in substrings to check if v is in the str string.

If any value v is in str, then some returns true.

Categories
JavaScript Answers

How to split a string into segments of n characters with JavaScript?

To split a string into segments of n characters with JavaScript, we call the match method.

For instance, we write

const str = "abcdefghijkl";
console.log(str.match(/.{1,3}/g));

to call str.match with a regex the matches groups of 1 to 3 characters in the str array.