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.

Categories
JavaScript Answers

How to generate a range within the supplied bounds with JavaScript?

To generate a range within the supplied bounds with JavaScript, we use the array keys method.

For instance, we write

const a = Array.from(Array(10).keys());

to call Array(10).keys() to get an array of indexes of the array with length 10.

Then we use Array.from to create a copy of the array and return it.

Categories
JavaScript Answers

How to remove empty elements from an array in JavaScript?

To remove empty elements from an array in JavaScript, we call the filter method.

For instance, we write

const arr = [1, 2, , 3, , -3, null, , 0, , undefined, 4, , 4, , 5, , 6, , , ,];
const filtered = arr.filter(Boolean);

to call arr.filter with Boolean to return an array with all the falsy values removed.

Categories
JavaScript Answers

How to get the last item in an array with JavaScript?

To get the last item in an array with JavaScript, we use the at method.

For instance, we write

if (locArray.at(-1) === "index.html") {
  // ...
} else {
  // ...
}

to get the last item from the locArray array with locArray.at(-1).