To get the first element of an array with JavaScript, we use index 0.
For instance, we write
const array = ["first", "second", "third", "fourth", "fifth"];
alert(array[0]);
to get the first entry of array with array[0].
To get the first element of an array with JavaScript, we use index 0.
For instance, we write
const array = ["first", "second", "third", "fourth", "fifth"];
alert(array[0]);
to get the first entry of array with array[0].
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.
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'.
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.
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.