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).

Categories
JavaScript Answers

How to merge two arrays in JavaScript and de-duplicate items?

To merge two arrays in JavaScript and de-duplicate items, we use the spread operator.

For instance, we write

const array1 = ["foo", "bar"];
const array2 = ["baz", "qux"];
console.log(Array.from(new Set([...array1, ...array2])));

to put all the items in array1 and array2 into a new array with the spread operator.

Then we create a new set from the array with the Set constructor to remove the duplicates.

And then we call Array.from with the set to convert it back to an array.

Categories
JavaScript Answers

How to create an array containing 1…N with JavaScript?

To create an array containing 1…N 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.