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.

Categories
JavaScript Answers

How to remove first and last element in a JavaScript array?

To remove first and last element in a JavaScript array, we use shift to remove the first item and pop to remove the last item.

For instance, we write

const fruits = ["Banana", "Orange", "Apple", "Mango"];

fruits.shift();
fruits.pop();

to call fruits.shift to remove the first item from fruits.

And we call fruits.pop to remove the last item from fruits.

Categories
JavaScript Answers

How to reorder arrays with JavaScript?

To reorder arrays with JavaScript, we can use destructuring syntax.

For instance, we write

const swapPositions = (array, a, b) => {
  [array[a], array[b]] = [array[b], array[a]];
};

let array = [1, 2, 3, 4, 5];
swapPositions(array, 0, 1);

to define the swapPositions function that assigns array[b] to array[a] and array[a] to array[b] with destructuring to swap the positions of the array entries at indexes a and b.

Then we call it with the array and the positions we want to swap.