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.

Categories
JavaScript Answers

How to use Array.includes() to find object in array with JavaScript?

To use Array.includes() to find object in array with JavaScript, we use the some method.

For instance, we write

const arr = [{ a: "b" }];
console.log(arr.some((item) => item.a === "b"));

to call arr.some with a callback that checks if item in arr has property a equal to 'b'.

If any object in arr has property a equal to 'b' then it returns true.

Categories
JavaScript Answers

How to split an array into two based on an index in JavaScript?

To split an array into two based on an index in JavaScript, we use the slice method.

For instance, we write

const ar = [1, 2, 3, 4, 5, 6];
const p1 = ar.slice(0, 4);
const p2 = ar.slice(4);

to call ar.slice with 0 and 4 to return an array with the items in ar between index 0 and 3 inclusive.

And we call ar.slice with 4 to return an array with the items in ar from index 4 to the end of the ar array.