0

If I have an array of locations like so:

["Roberts", "baltimore", "Maryland", "21212"],
["Adams", "baltimore", "Maryland", "21212"],
["Joes", "philadelphia", "Pennsylvania", "30333"],
["Carls", "new york", "New York", "40415"]

Using Javascript or Jquery, How would I first sort them by state, then by name, so the resulting order would be:

["Adams", "baltimore", "Maryland", "21212"],
["Roberts", "baltimore", "Maryland", "21212"],
["Carls", "new york", "New York", "40415"],
["Joes", "philadelphia", "Pennsylvania", "30333"]
6
  • 3
    The result list doesn't appear to be sorted by state. Commented Feb 18, 2014 at 15:10
  • 3
    The data doesn't appear to be in any JS data format. Commented Feb 18, 2014 at 15:10
  • What problem are you having? Reading whatever file the data is stored in? Parsing your custom data format? Finding the documentation for the Array sort method? Commented Feb 18, 2014 at 15:11
  • 1
    Um, that is not valid JavaScript. Commented Feb 18, 2014 at 15:11
  • Has been asked so many times... stackoverflow.com/q/16164078/989121 Commented Feb 18, 2014 at 15:17

2 Answers 2

4

If we start with an actual array:

var orig = [
  ["Roberts", "baltimore", "Maryland", "21212"],
  ["Adams", "baltimore", "Maryland", "21212"],
  ["Joes", "philadelphia", "Pennsylvania", "30333"],
  ["Carls", "new york", "New York", "40415"]
];

We can sort it like so:

var sorted = orig.sort(
  function(a, b) {
    // compare states
    if (a[2] < b[2])
      return -1;
    else if (a[2] > b[2])
      return 1;

    // states were equal, try names
    if (a[0] < b[0])
      return -1;
    else if (a[0] > b[0])
      return 1;

    return 0;
  }
);

which returns:

[
  ["Adams","baltimore","Maryland","21212"],
  ["Roberts","baltimore","Maryland","21212"],
  ["Carls","new york","New York","40415"],     
  ["Joes","philadelphia","Pennsylvania","30333"]
]

Example: http://codepen.io/paulroub/pen/ADihk

Sign up to request clarification or add additional context in comments.

Comments

0

Try this answer (see at the end), but will need an explicit custom criteria:

""" compare(object1, object2)
if object1.state > object2.state then object1 is greater (1)
if object1.state < object2.state then object2 is greater (-1)
if object1.name > object2.name then object1 is greater (1)
if object1.name < object2.name then object2 is greater (-1)
objects are equal or, at least, not sortable by the criteria you exposed.
"""

How to sort an array of objects with jquery or javascript

(note that "array" in array.sort refers your array of objects, and provided your object have actually the field names "name" and "state", since you did not actually specify them - actually they have no fields, so they are not objects nor arrays).

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.