Categories
JavaScript Answers

How to remove array element by value with JavaScript?

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.

Categories
JavaScript Answers

How to flatten an array of arrays of objects with JavaScript?

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.

Categories
JavaScript Answers

How to splice an array in half no matter the size with JavaScript?

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.

Categories
JavaScript Answers

How to merge array of objects by property using JavaScript Lodash?

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.

Categories
JavaScript Answers

How to get max and min value from array in JavaScript?

To get max and min value from array in JavaScript, we the Math.max and Math.min methods.

For instance, we write

const array = [1, 3, 2];
const max = Math.max(...array);
const min = Math.min(...array);

to call Math.max with the array entries as arguments to return the max value from array.

And we call Math.min with the array entries as arguments to return the min value from array.

The spread operator spreads the array entries as arguments.