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.

Categories
JavaScript Answers

How to generate all combinations of elements in a single array in pairs with JavaScript?

To generate all combinations of elements in a single array in pairs with JavaScript, we call the flatMap and slice method.

For instance, we write

const array = ["apple", "banana", "lemon", "mango"];
const result = array.flatMap((v, i) =>
  array.slice(i + 1).map((w) => v + " " + w)
);

to call array.flatMap with a callback that returns a sliced version of the array with slice with items from index i + 1 to the end of the array.

And then we call map on the sliced array and combined the item v and w into a string.

flatMap will flatten the arrays returned into a single level array with the results.

Categories
JavaScript Answers

How to apply a function to each object in a JavaScript array

To apply a function to each object in a JavaScript array, we use the map method.

For instance, we write

const newArray = oldArray.map((e) => {
  e.data = e.data.split(",");
  return e;
});

to call oldArray.map with a callback that sets the e.data property in the oldArray to a new value.

Then we return new object e.

An array with each object e in oldArray modified is returned.