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.

Categories
JavaScript Answers

How to paginate JavaScript array?

To paginate JavaScript array, we use the slice method.

For instance, we write

const paginate = (array, pageSize, pageNumber) => {
  return array.slice((pageNumber - 1) * pageSize, pageNumber * pageSize);
};

console.log(paginate([1, 2, 3, 4, 5, 6], 2, 2));

to define the pagination function that calls array.slice with the start and end index of the chunk of the array to return.

The item at the end index itself is not included with the returned array.

Categories
JavaScript Answers

How to remove an object from array with JavaScript MongoDB?

To remove an object from array with JavaScript MongoDB, we call update with the $pull operator.

For instance, we write

db.myCollection.update(
  { _id: ObjectId("5150a1199fac0e6910000002") },
  { $pull: { items: { id: 23 } } },
  false,
  true
);

to call update to get the element with object ID 5150a1199fac0e6910000002 and remove the item in items with _id 23 from each entry with $pull.

The 3rd argument is false means we disable upsert.

And the 4th argument is true means we do the operation on all items entries.

Categories
JavaScript Answers

How to sort 2-dimensional array by column value with JavaScript?

To sort 2-dimensional array by column value with JavaScript, we can get the value by the index.

For instance, we write

const arr = [
  [12, "AAA"],
  [12, "BBB"],
  [12, "CCC"],
  [28, "DDD"],
  [18, "CCC"],
  [12, "DDD"],
  [18, "CCC"],
  [28, "DDD"],
  [28, "DDD"],
  [58, "BBB"],
  [68, "BBB"],
  [78, "BBB"],
];

const sorted = arr.sort((a, b) => {
  return a[0] - b[0];
});

to call sort with a callback that gets the first value from each nested array and compare them to sort the entries by the first value and return the sorted array.