Categories
JavaScript Answers

How to do the opposite of includes with JavaScript arrays?

To do the opposite of includes with JavaScript arrays, we negate the return value of includes.

For instance, we write

const res = filteredResult.filter((e) => !e.selectedFields.includes("Red"));

to call filter with a callback that checks if object e‘s selectedFields property in filteredResult being looped through doesn’t include 'Red'.

Categories
JavaScript Answers

How to convert array into string without comma and separated by space in JavaScript without concatenation?

To convert array into string without comma and separated by space in JavaScript without concatenation, we call the join method.

For instance, we write

const str = array.join(" ");

to call array.join with a space as the separator to return a string with the items in array joined together.

Categories
JavaScript Answers

How to multiply each member of an array by a scalar in JavaScript?

To multiply each member of an array by a scalar in JavaScript, we use the map method.

For instance, we write

const a = [1, 2, 3].map((x) => {
  return x * 5;
});

to call map with a callback to return x in the [1, 2, 3] array being looped through by 5.

An array with each value in [1, 2, 3] multiplied by 5 is returned.

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.