Categories
JavaScript Answers

How to reverse array in JavaScript without mutating original array?

To reverse array in JavaScript without mutating original array, we copy the array before calling reverse.

For instance, we write

const newArray = [...array].reverse();

to copy the array with the spread operator.

And then we call reverse to reverse the copied array.

Categories
JavaScript Answers

How to sum a property value in an array with JavaScript?

To sum a property value in an array with JavaScript, we use the map and reduce methods.

For instance, we write

const traveler = [
  { description: "Senior", amount: 50 },
  { description: "Senior", amount: 50 },
  { description: "Adult", amount: 75 },
  { description: "Child", amount: 35 },
  { description: "Infant", amount: 25 },
];

const sum = traveler
  .map((item) => item.amount)
  .reduce((prev, next) => prev + next);

to call traveler.map with a callback to get the amount property from each entry and put it in the returned array.

And then we call reduce with a callback to sum up the values from the array returned by map.

Categories
JavaScript Answers

How to count the occurrences / frequency of array elements with JavaScript?

To count the occurrences / frequency of array elements with JavaScript, we use a for-of loop.

For instance, we write

const arr = [5, 5, 5, 2, 2, 2, 2, 2, 9, 4];
const counts = {};

for (const num of arr) {
  counts[num] = counts[num] ? counts[num] + 1 : 1;
}

to define the counts object.

Then we use a for-of loop to loop through the arr array and set counts[num] to counts[num] + 1 if it’s already set and 1 otherwise.

Categories
JavaScript Answers

How to convert JavaScript NodeList to an array?

To convert JavaScript NodeList to an array, we use the Array.from method.

For instance, we write

const myArray = Array.from(nl);

to call Array.from with nl to convery the nl node list into an array.

Categories
JavaScript Answers

How to prepend a value to an array with JavaScript?

To prepend a value to an array with JavaScript, we call the unshift method.

For instance, we write

a.slice().unshift(0);

to call a.slice to make copy of the a array.

And then we call unshift on the copied array to prepend 0 into the array.