Categories
JavaScript Answers

How to reduce an empty array with JavaScript?

To reduce an empty array with JavaScript, we should set the initial value returned by reduce.

For instance, we write

const val = [].reduce(
  (previousValue, currentValue) => previousValue + currentValue,
  0
);

to call reduce on an empty array with a callback that returns the partial sum of the array values.

We set the initial value of previousValue to 0 by calling it with the 2nd argument to avoid the reduce empty array error.

Categories
JavaScript Answers

How to get objects value if its name contains dots with JavaScript?

To get objects value if its name contains dots with JavaScript, we can use square brackets.

For instance, we write

const mydata = {
  list: [
    {
      "points.bean.pointsBase": [
        { time: 2000, caption: "caption text", duration: 5000 },
        { time: 6000, caption: "caption text", duration: 3000 },
      ],
    },
  ],
};
const smth = mydata.list[0]["points.bean.pointsBase"][0].time;

to get the first entry in list with mydata.list[0]

And we get the "points.bean.pointsBase" property with ["points.bean.pointsBase"].

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.