Categories
JavaScript Answers

How to split a long array into smaller arrays with JavaScript?

To split a long array into smaller arrays with JavaScript, we use the chunk method.

For instance, we write

const chunks = _.chunk(["a", "b", "c", "d"], 2);

to call the chunk function to split the ["a", "b", "c", "d"] into chunks of 2 and return an array with the chunks.

Categories
JavaScript Answers

How to use JavaScript Lodash to sort array of object by value?

To use JavaScript Lodash to sort array of object by value, we use the sortBy method.

For instance, we write

const myArray = [
  {
    id: 25,
    name: "Anakin Skywalker",
    createdAt: "2022-04-12T12:48:55.000Z",
    updatedAt: "2022-04-12T12:48:55.000Z",
  },
  {
    id: 1,
    name: "Luke Skywalker",
    createdAt: "2022-04-12T11:25:03.000Z",
    updatedAt: "2022-04-12T11:25:03.000Z",
  },
];

const myOrderedArray = _.sortBy(myArray, (o) => o.name);

to call sortBy with myArray and a callback that returns the name property value to sort by the name property.

An array with the sorted values is returned.

Categories
JavaScript Answers

How to compare JavaScript array of objects to get min / max?

To compare JavaScript array of objects to get min / max, we call the Math.min and Math.max methods.

For instance, we write

const myArray = [
  { id: 1, cost: 200 },
  { id: 2, cost: 1000 },
  { id: 3, cost: 50 },
  { id: 4, cost: 500 },
];

const min = Math.min(...myArray.map((item) => item.cost));
const max = Math.max(...myArray.map((item) => item.cost));

to call myArray.map to get the cost property values in an array.

Then we spread the values as arguments of Math.min and Math.max to get the min and max values.

Categories
JavaScript Answers

How to truncate an array with JavaScript?

To truncate an array with JavaScript, we use the slice method.

For instance, we write

let arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
arr = arr.slice(0, 4);
console.log(arr);

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

And we assign the returned array back to arr to update it.

Categories
JavaScript Answers

How to convert a JavaScript iterable to an array?

To convert a JavaScript iterable to an array, we use the spread operator.

For instance, we write

const x = new Set([1, 2, 3, 4]);
const z = [...x];

to create a set with the Set constructor.

Then we convert the set to an array with the spread operator.