To find length or size of an array in JavaScript, we use the length property.
For instance, we write
const arr = [];
arr[1] = 2;
arr[2] = 3;
console.log(arr.length);
to create the array arr.
Then we get its size with arr.length.
To find length or size of an array in JavaScript, we use the length property.
For instance, we write
const arr = [];
arr[1] = 2;
arr[2] = 3;
console.log(arr.length);
to create the array arr.
Then we get its size with arr.length.
To remove array element by value with JavaScript. we use the indexOf and splice methods.
For instance, we write
const arr = ["orange", "red", "black", "white"];
const index = arr.indexOf("red");
if (index >= 0) {
arr.splice(index, 1);
}
to call arr.indexOf to get the index of the first instance of 'red' in arr.
Then we check if index is bigger than 0 to check if it’s found.
If it is, then we call splice with index and 1 to return the item in arr at index.
To flatten an array of arrays of objects with JavaScript, we use the flat method.
For instance, we write
const flattened = [["object1"], ["object2"]].flat();
to return a flattened version of the [["object1"], ["object2"]] array with flat.
To splice an array in half no matter the size with JavaScript, we use the slice method.
For instance, we write
const halfLength = Math.ceil(arrayName.length / 2);
const leftSide = arrayName.slice(0, halfLength);
to call Math.ceil with arrayName.length / 2 to get the index of the middle element.
Then we call slice with 0 and halfLength to return the first half of the arrayName array.
To merge array of objects by property using JavaScript Lodash, we use the unionBy function.
For instance, we write
const original = [
{ label: "private", value: "private@johndoe.com" },
{ label: "work", value: "work@johndoe.com" },
];
const update = [
{ label: "private", value: "me@johndoe.com" },
{ label: "school", value: "schol@johndoe.com" },
];
const result = _.unionBy(update, original, "label");
to call unionBy with the update and original arrays and merge the objects into one by matching the label property.
A new array with the merged objects is returned.