sort an array of arrays by the name field in javascript

To sort an array of arrays by the name field in JavaScript, you can use the sort() method and specify a compare function that compares the name field of each array.

Here's an example:

index.tsx
// Example array of arrays with name field
const arr = [
  ["John", 25],
  ["Tim", 33],
  ["Sarah", 19],
  ["David", 41],
];

// Sort array by name (first element)
arr.sort((a, b) => a[0].localeCompare(b[0]));

console.log(arr);
// Output: [["David", 41], ["John", 25], ["Sarah", 19], ["Tim", 33]]
298 chars
14 lines

In the compare function, we use localeCompare() method to compare two strings (a[0] and b[0]) and return -1, 0, or 1 depending on whether a is less than, equal to, or greater than b.

gistlibby LogSnag