Categories
JavaScript Answers

How to remove first and last element in a JavaScript array?

To remove first and last element in a JavaScript array, we use shift to remove the first item and pop to remove the last item.

For instance, we write

const fruits = ["Banana", "Orange", "Apple", "Mango"];

fruits.shift();
fruits.pop();

to call fruits.shift to remove the first item from fruits.

And we call fruits.pop to remove the last item from fruits.

Categories
JavaScript Answers

How to reorder arrays with JavaScript?

To reorder arrays with JavaScript, we can use destructuring syntax.

For instance, we write

const swapPositions = (array, a, b) => {
  [array[a], array[b]] = [array[b], array[a]];
};

let array = [1, 2, 3, 4, 5];
swapPositions(array, 0, 1);

to define the swapPositions function that assigns array[b] to array[a] and array[a] to array[b] with destructuring to swap the positions of the array entries at indexes a and b.

Then we call it with the array and the positions we want to swap.

Categories
JavaScript Answers

How to convert uint8 array to base64 encoded string with JavaScript?

To convert uint8 array to base64 encoded string with JavaScript, we use the Buffer.from method.

For instance, we write

const u8 = new Uint8Array([65, 66, 67, 68]);
const b64 = Buffer.from(u8).toString("base64");

to call Buffer.from with the u8 Uint8Array to convert it to a buffer.

Then we call toString with 'base64' to convert it to a base64 string.

Categories
JavaScript Answers

How to filter array with multiple conditions with JavaScript?

To filter array with multiple conditions with JavaScript, we call the filter method.

For instance, we write

const filteredUsers = users.filter(
  (obj) => obj.name === filter.name && obj.address === filter.address
);

to call users.filter with a callback that gets the items with the name property of the obj being looped through equal to filter.name.

And we get the item in users with address property equal to filter.address.

Categories
JavaScript Answers

How to move an item of an array to the front with JavaScript?

To move an item of an array to the front with JavaScript, we can use the spread operator.

For instance, we write

const data = ["email", "role", "type", "name"];

const newData = [
  data.find((item) => item === "role"),
  ...data.filter((item) => item !== "role"),
];

to call data.find to find the value equals to 'role' and put it in front of the array.

Then we call data.filter to get the rest of the items in an array and spread them at the end of the array.