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.

Categories
JavaScript Answers

How to insert an array inside another array with JavaScript?

To insert an array inside another array with JavaScript, we use the splice method.

For instance, we write

const a1 = [1, 2, 3, 4, 5];
const a2 = [21, 22];
a1.splice(2, 0, ...a2);

to call splice with the entries in the a2 array spread as arguments of splice to insert the entries at index 2 of a1.

Then entries in a1 after index 2 are moved to the end of the array.

Categories
JavaScript Answers

How to convert integer array to string array in JavaScript?

To convert integer array to string array in JavaScript, we call the map method.

For instance, we write

const sphValues = [1, 2, 3, 4, 5];
const mapped = sphValues.map(String);

to call map with String to return an array with the numbers in the sphValues array converted to strings.