Categories
JavaScript Answers

How to extend an existing JavaScript array with another array, without creating a new array?

To extend an existing JavaScript array with another array, without creating a new array, we call the push method.

For instance, we write

const a = [1, 2];
const b = [3, 4, 5];
a.push(...b);

to call a.push with the items in b as arguments to append the items in b into a in the order they’re listed.

We use the spread operator to call push with the entries in b as arguments.

Categories
JavaScript Answers

How to create a two dimensional array in JavaScript?

To create a two dimensional array in JavaScript, we put arrays inside an array.

For instance, we write

const items = [
  [1, 2],
  [3, 4],
  [5, 6],
];
console.log(items[0][0]);
console.log(items[0][1]);
console.log(items[1][0]);
console.log(items[1][1]);

to put arrays inside the items array.

Then we access the first array in item‘s items with

console.log(items[0][0]);
console.log(items[0][1]);

We access the 2nd array in item‘s items with

console.log(items[1][0]);
console.log(items[1][1]);
Categories
JavaScript Answers

How to find the sum of an array of numbers with JavaScript?

To find the sum of an array of numbers with JavaScript, we call the reduce method.

For instance we write

const sum = [1, 2, 3].reduce((partialSum, a) => partialSum + a, 0);
console.log(sum);

to call reduce with a function that returns the partialSum plus the number a in the array being looped through.

We set the initial value of partialSum to 0 with the 2nd argument.

The sum is returned and it’s 6.

Categories
JavaScript Answers

How to compare arrays in JavaScript?

To compare arrays in JavaScript, we use the JSON.stringify method.

For instance, we write

const isSame = JSON.stringify(a1) === JSON.stringify(a2);

to convert arrays a1 and a2 to JSON strings with JSON.stringify.

And then we compare the strings with ===.

Categories
JavaScript Answers

How to merge/flatten an array of arrays with JavaScript?

To merge/flatten an array of arrays with JavaScript, we call the flat method.

For instance, we write

const arrays = [["$6"], ["$12"], ["$25"], ["$25"], ["$18"], ["$22"], ["$10"]];
const merge3 = arrays.flat(1);
console.log(merge3);

to call arrays.flat with 1 to flatten the arrays array 1 level deep.

The returned flattened array is assigned to merge3.