Categories
JavaScript Answers

How to change values in array when using forEach with JavaScript?

To change values in array when using forEach with JavaScript, we can assign the new value.

For instance, we write

const data = [1, 2, 3, 4];
data.forEach((item, i, self) => (self[i] = item + 10));

to call forEach with a callback that has the i and self parameters.

In it, we assign self[i] to the new value of the array.

self is the data array.

i is the index of the entry being iterated through.

item is the entry being iterated through.

Categories
JavaScript Answers

How to convert an array to JSON with JavaScript?

To convert an array to JSON with JavaScript, we call the JSON.stringify method.

For instance, we write

const myJsonString = JSON.stringify(yourArray);

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

Categories
JavaScript Answers

How to convert the arguments object to an array in JavaScript?

To convert the arguments object to an array in JavaScript, we should replace it with the rest operator.

For instance, we write

const sortArgs = (...args) => {
  return args.sort((a, b) => {
    return a - b;
  });
};

to define the sortArgs function.

We use the spread operator to convert the arguments into an array with the ... rest operator.

args then has all the arguments we called sortArgs with.

And then we call args.sort to sort the arguments and returned a new array with the sorted values.

Categories
JavaScript Answers

How to get character array from a string with JavaScript?

To get character array from a string with JavaScript, we use the spread operator.

For instance, we write

const arr = [...str];

to spread the str string into a character array with the spread operator.

Categories
TypeScript Answers

How to check whether an array contains a string in TypeScript?

To check whether an array contains a string in TypeScript, we call the includes method.

For instance, we write

console.log(channelArray.includes("three"));

to check if the channelArray has 'three' in it with includes.