Categories
JavaScript Answers

How to convert byte array to Hex string conversion in JavaScript?

To convert byte array to Hex string conversion in JavaScript, we use the Array.from method.

For instance, we write

const toHexString = (byteArray) => {
  return Array.from(byteArray, (byte) => {
    return `0${(byte & 0xff).toString(16).slice(-2)}`;
  }).join("");
};

to define the toHexString function.

In it, we call Array.from with byteArray and a callback to convert each byte to a hex string.

The callback does a bitwise and with 0xff and then convert that to a hex string with toString called with 16.

And then we get the substring from the 3rd last index to the end of the string with slice.

Then we join the array of hex strings into a string with join.

Categories
JavaScript Answers

How to find an object in an array by one of its properties with JavaScript?

To find an object in an array by one of its properties with JavaScript, we call the find method.

For instance, we write

const newData = [
  { investor: "Sue", stocks: 0, options: 0, savings: 0 },
  { investor: "Rob", stocks: 0, options: 0, savings: 0 },
  { investor: "Liz", stocks: 0, options: 0, savings: 0 },
];
const investor = "Rob";
const res = newData.find((x) => x.investor === investor);

to call newData.find with a callback that checks whether the investor property in the object being looped through equals to investor.

The first instance of the object where the condition is returned.

Categories
JavaScript Answers

How to select all other values in an array except the ith element with JavaScript?

To select all other values in an array except the ith element with JavaScript, we use the filter method.

For instance, we write

const items = [1, 2, 3, 4, 5, 6];
const current = 2;
const itemsWithoutCurrent = items.filter((x) => {
  return x !== current;
});

to call items.filter with a callback that checks if x isn’t equal to current and return all the elements in items where x isn’t equal to current.

Categories
JavaScript Answers

How to create a dynamic array of strings with JavaScript?

To create a dynamic array of strings with JavaScript, we just add or remove items as we want.

For instance, we write

const myArray = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
myArray.push(11);
const popped = myArray.pop();

to call myArray.push with 11 to push a 11 as the last item in myArray.

And we call myArray.pop to remove the last item in myArray and return the removed item.

Categories
JavaScript Answers

How to use reduce() to find min and max values with JavaScript?

To use reduce() to find min and max values with JavaScript, we use the spread operator.

For instance, we write

const min = Math.min(...items);
const max = Math.max(...items);

to call Math.min with the values in the items array spread as arguments to get the min value in the items array.

And we call Math.max with the values in the items array spread as arguments to get the max value in the items array.