Categories
JavaScript Answers

How to prevent adding duplicate keys to a JavaScript array?

To prevent adding duplicate keys to a JavaScript array, we use sets.

For instance, we write

const set = new Set();
set.add(1);
set.add(2);
set.add(3);

console.log(set);

to create a new set with the Set constructor.

Then we call add to add the entries into the set.

Duplicate entries won’t be added to the set with add.

Categories
JavaScript Answers

How to replace elements in array with elements of another array with JavaScript?

To replace elements in array with elements of another array with JavaScript, we use the splice method.

For instance, we write

const a = [1, 2, 3, 4, 5];
const b = [10, 20, 30];
a.splice(0, b.length, ...b);

to call a.splice with 0, b.length and the elements in b as arguments to replace the items in a between index 0 and b.length - 1 with the items in b in place.

Categories
JavaScript Answers

How to sort an array of objects by date with JavaScript?

To sort an array of objects by date with JavaScript, we call the sort method.

For instance, we write

const recent = [
  { id: 123, age: 12, start: "10/17/2022 13:07" },
  { id: 13, age: 62, start: "07/30/2022 16:30" },
];
const sorted = recent.sort((a, b) => {
  return new Date(a.start).getTime() - new Date(b.start).getTime();
});

to call recent.sort with a callback that gets the timestamp of the start property of 2 of the objects in recent with getTime and then compare them by subtracting them to return a number that determines the sorting order.

a is sorted after b if the number returned is bigger than 0.

a is sorted before b if the number returned is less than 0.

And the original order is kept if it’s 0.

Categories
JavaScript Answers

How to use getElementById with multiple IDs in JavaScript?

To use getElementById with multiple IDs in JavaScript, we use the querySelectorAll method.

For instance, we write

const els = document.querySelectorAll(
  "#myCircle1, #myCircle2, #myCircle3, #myCircle4"
);

to call querySelectorAll with the selector for the elements we want to select separated by commas.

A node list with all the selected elements is returned.

Categories
JavaScript Answers

How to push with a multidimensional array with JavaScript?

To push with a multidimensional array with JavaScript, we call the push method.

For instance, we write

arrayToPush.push([value1, value2, valueN]);

to call arrayToPush.push with an array of values to append the array as the last element of arrayToPush.