0

My goal is to sort the following array lexiographically. Take the following array:

['abc', 'xyz', 'hij', 'def']

In the end it should look like this:

['abc', 'def', 'hij', 'xyz']

I found this question, which shows how to implement it on an array of objects, but I don't know how to convert the code that it sorts a "normal" array.

Philip F.
  • 1,167
  • 1
  • 18
  • 33

2 Answers2

2

You can use array sort:

var array = ['abc', 'xyz', 'hij', 'def'];
console.log(array.sort());
Buddy Christ
  • 1,364
  • 8
  • 22
1

As you can see in the ECMAScript Language Specification, lexicographic ordering is the default for strings.

It is, in fact, the default for numbers, too, which is incredibly annoying:

const ns = [4, 18, 8, 6, 1, 15, 7, 16, 17, 9, 13, 2, 3, 11, 12, 14, 20, 19, 10, 5];

console.log(ns.sort());
// [1, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 2, 20, 3, 4, 5, 6, 7, 8, 9]

So, you can simply use Array.prototype.sort with the default comparator, like this:

const strings = ['abc', 'xyz', 'hij', 'def'];

console.log(strings.sort());
// ['abc', 'def', 'hij', 'xyz']

As you can see in the specification for Array.prototype.sort, it delegates to the Abstract Relation Comparison Operation, which in step #3 performs a lexicographic compare.

Community
  • 1
  • 1
Jörg W Mittag
  • 363,080
  • 75
  • 446
  • 653