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.

Categories
JavaScript Answers

How to sort JavaScript array by two numeric fields?

To sort JavaScript array by two numeric fields, we call the sort method.

For instance, we write

const sorted = grouperArray.sort((a, b) => {
  return a.size - b.size || a.glow - b.glow;
});

to call sort with a callback that compares the items by their size property values and glow property values.

Categories
JavaScript Answers

How to upload multiple files using JavaScript formData?

To upload multiple files using JavaScript formData, we call append with an array key.

For instance, we write

fd.append("fileToUpload[]", document.getElementById("fileToUpload").files[0]);

to call fd.append with the "fileToUpload[]" array key and a file we get from a file input.

We get the file input with getElementById.

And we get the selected files from the files property.

Categories
JavaScript Answers

How to sort a JavaScript array based on the length of each element?

To sort a JavaScript array based on the length of each element, we call the sort method.

For instance, we write

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

to call arr.sort with a callback that subtracts the length property values of b and a to return an array with the strings in arr sorted by length in descending order.