Categories
JavaScript Answers

How to use map() on an array in reverse order with JavaScript?

To use map() on an array in reverse order with JavaScript, we make a copy before we reverse the array.

For instance, we write

myArray
  .slice(0)
  .reverse()
  .map((a) => {
    //...
  });

to call slice to make a copy of myArray and return it.

And then we call reverse to reverse the copied array.

Then we call map to map the entries of the reversed array.

Categories
JavaScript Answers

How to unpack array into separate variables in JavaScript?

To unpack array into separate variables in JavaScript, we use destructuring.

For instance, we write

const arr = ["one", "two"];
const [one, two] = arr;

to assign the entries in arr into their own variables with the destructuring syntax.

So one is 'one' and two is 'two'.

Categories
JavaScript Answers

How to check if two arrays have the same values with JavaScript?

To check if two arrays have the same values with JavaScript, we sort them before comparing them.

For instance, we write

const array1 = [
  10, 6, 19, 16, 14, 15, 2, 9, 5, 3, 4, 13, 8, 7, 1, 12, 18, 11, 20, 17,
];
const array2 = [
  12, 18, 20, 11, 19, 14, 6, 7, 8, 16, 9, 3, 1, 13, 5, 4, 15, 10, 2, 17,
];

if (array1.sort().join(",") === array2.sort().join(",")) {
  console.log("same members");
}

to call sort to sort the numbers in the arrays and then we call join to join the entries with commas to form a string.

Then we compare them with === to see if they’re the same.

Categories
JavaScript Answers

How to convert JavaScript array to a string?

To convert JavaScript array to a string, we use the JSON.stringify method.

For instance, we write

const a = ["a", "b", "c"];
const str = JSON.stringify(a);

to call JSON.stringify with a to convert the a array to a JSON string.

Categories
JavaScript Answers

How to convert base64 string to ArrayBuffer with JavaScript?

To convert base64 string to ArrayBuffer with JavaScript, we use the Buffer.from method.

For instance, we write

const myBuffer = Buffer.from(someBase64String, "base64");

to call Buffer.from with the someBase64String base64 string and 'base64' to convert the base 64 string to a buffer.