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.

Categories
JavaScript Answers

How to reduce an empty array with JavaScript?

To reduce an empty array with JavaScript, we should set the initial value returned by reduce.

For instance, we write

const val = [].reduce(
  (previousValue, currentValue) => previousValue + currentValue,
  0
);

to call reduce on an empty array with a callback that returns the partial sum of the array values.

We set the initial value of previousValue to 0 by calling it with the 2nd argument to avoid the reduce empty array error.

Categories
JavaScript Answers

How to get objects value if its name contains dots with JavaScript?

To get objects value if its name contains dots with JavaScript, we can use square brackets.

For instance, we write

const mydata = {
  list: [
    {
      "points.bean.pointsBase": [
        { time: 2000, caption: "caption text", duration: 5000 },
        { time: 6000, caption: "caption text", duration: 3000 },
      ],
    },
  ],
};
const smth = mydata.list[0]["points.bean.pointsBase"][0].time;

to get the first entry in list with mydata.list[0]

And we get the "points.bean.pointsBase" property with ["points.bean.pointsBase"].