Categories
JavaScript Answers

How to obtain smallest value from array in JavaScript?

To obtain smallest value from array in JavaScript, we use the Math.min method.

For instance, we write

const arr = [14, 58, 20, 77, 66, 82, 42, 67, 42, 4];
const min = Math.min(...arr);

to call Math.min with the entries in the arr array as arguments to get the min number from the arr array and return it.

We use the spread operator to spread the arr values as arguments.

Categories
JavaScript Answers

How to add named properties to a JavaScript array as if it were an object?

To add named properties to a JavaScript array as if it were an object, we can add them directly to the array with assignment.

For instance, we write

const myArray = [];
myArray.a = "Athens";

to define the myArray array and assign the a property of the array to 'Athens'.

We can do this because arrays are objects.

Categories
JavaScript Answers

How to sort objects by property values with JavaScript?

To sort objects by property values with JavaScript, we use the sort method.

For instance, we write

const cars = [
  {
    name: "Honda",
    speed: 80,
  },
  {
    name: "BMW",
    speed: 180,
  },
  {
    name: "Trabi",
    speed: 40,
  },
  {
    name: "Ferrari",
    speed: 200,
  },
];

const soreted = cars.sort((a, b) => {
  return a.speed - b.speed;
});

to call cars.sort with a callback that sorts the objects in the cars array by the speed property value in ascending order.

Categories
JavaScript Answers

How to sort arrays numerically by object property value with JavaScript?

To sort arrays numerically by object property value with JavaScript, we use the sort method.

For instance, we write

const sorted = myArray.sort((a, b) => a.distance - b.distance);

to call myArray.sort with a callback that sorts by the distance property of each object in myArray in ascending order.

Categories
JavaScript Answers

How to select where in array of _id with JavaScript MongoDB?

To select where in array of _id with JavaScript MongoDB, we use the $in operator.

For instance, we write

db.collection.find({ _id: { $in: [1, 2, 3, 4] } });

to call find with the $in operator to return the entries with _id 1, 2, 3, and 4 with find in the collection collection.