Categories
JavaScript Answers

How to swap array elements with JavaScript?

To swap array elements with JavaScript, we use destructuring.

For instance, we write

[arr[0], arr[1]] = [arr[1], arr[0]];

to ass arr[1] to arr[0]and assignarr[0]toarr[1]` with destructuring.

Categories
JavaScript Answers

How to loop through an array containing objects and access their properties with JavaScript?

To loop through an array containing objects and access their properties with JavaScript, we use the forEach method.

For instance, we write

yourArray.forEach((arrayItem) => {
  const x = arrayItem.prop + 2;
  console.log(x);
});

to call forEach with a callback that gets the prop property value from the arrayItem being looped through.

And then we add 2 to it assign the sum to x.

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.