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.

Categories
JavaScript Answers

How to convert a NodeList to an array with JavaScript?

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

For instance, we write

const spanList = [...document.querySelectorAll("span")];

to select all spans and put them in a node list with querySelectorAll.

And then we spread the node list entries into an array with the spread operator.

Categories
JavaScript Answers

How to check if the JavaScript array of objects have duplicate property values?

To check if the JavaScript array of objects have duplicate property values, we can compare its size to its set equivalent.

For instance, we write

const values = [
  { name: "name1" },
  { name: "name2" },
  { name: "name3" },
  { name: "name1" },
];

const uniqueValues = new Set(values.map((v) => v.name));

if (uniqueValues.size < values.length) {
  console.log("duplicates found");
}

to create a set with the Set constructor with an array of name property values from each object.

Then we compare the size of the set to the length of the array to check if there’re any duplicates.

If the size of the set is smaller than the array’s length, then there are duplicates.