Jeff Goes
Jeff Goes

Reputation: 555

How do I sort this Array in alphabetical order in Javascript?

So I have this array:

[[21, "Bowling Ball"], [2, "Dirty Sock"], [1, "Hair Pin"], [5, "Microphone"]], [3, "Half-Eaten Apple"],[7, "Toothpaste"]];

I want to sort the element of this array in alphabetic order accordingly to the second element. So I wanted to be ordered like this:

[[21, "Bowling Ball"], [2, "Dirty Sock"], [1, "Hair Pin"], [3, "Half-Eaten Apple"], [5, "Microphone"]], [7, "Toothpaste"]];

What can I do to accomplish this in javascript?

Upvotes: 0

Views: 474

Answers (2)

Nina Scholz
Nina Scholz

Reputation: 386578

With a proper array and the use of the second item, you could use Array#sort with hint for Sorting non-ASCII characters for String#localeCompare for comparing strings.

var array = [[21, "Bowling Ball"], [2, "Dirty Sock"], [1, "Hair Pin"], [5, "Microphone"], [3, "Half-Eaten Apple"], [7, "Toothpaste"]];

array.sort(function (a, b) {
    return a[1].localeCompare(b[1]);
});

console.log(array);

Upvotes: 4

elqueso101
elqueso101

Reputation: 84

let stuff = [
  [21, "Bowling Ball"],
  [2, "Dirty Sock"],
  [1, "Hair Pin"],
  [5, "Microphone"],
  [3, "Half-Eaten Apple"],
  [7, "Toothpaste"]];

This can be accomplished easily by sorting the array items by using the String.prototype.localeCompare() method to put the items in alphabetical order.

stuff.sort((item1, item2) => item1[1].localeCompare(item2[1]));

Upvotes: 0

Related Questions