Categories
JavaScript Answers

How to sort an array without mutating the original array with JavaScript?

To sort an array without mutating the original array with JavaScript, we make a copy of the original array.

For instance, we write

const sorted = [...arr].sort();

to make a copy of arr with the spread operator.

And then we call sort to sort the copied array.

Categories
JavaScript Answers

How to remove array element based on object property with JavaScript?

To remove array element based on object property with JavaScript, we use the filter method.

For instance, we write

const newArray = myArray.filter((obj) => {
  return obj.field !== "money";
});

to call myArray.filter with a callback that return an array with objects that has the field property not equal to 'money'.

Categories
JavaScript Answers

How to convert an object to an array of key-value pairs in JavaScript?

To convert an object to an array of key-value pairs in JavaScript, we call the Object.entries method.

For instance, we write

const obj = { 1: 5, 2: 7, 3: 0, 4: 0, 5: 0, 6: 0 };
const result = Object.entries(obj);

console.log(result);

to call Object.entries with obj to return an array with array of key-value pairs in obj.

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.