-4

I have an array like this.

var word_list = [
    {text: "Lorem", weight: 13},
    {text: "Ipsum", weight: 10},
    {text: "Dolor", weight: 9},
    {text: "Sit", weight: 8},
    {text: "Amet", weight: 6},
    {text: "Consectetur", weight: 5}
];

How can I sort this with "text" or "weight".

Prasanth
  • 59
  • 2
  • 6
  • Before you proceed on your JavaScript journey, make sure you have the terminology right. It's important. JavaScript has nothing called an "associative array". It has **objects**. Once you learned that, it would be much easier to search for answers to questions like this. For instance, you could search for "sort javascript object by property", and you would find hundreds if not thousands of answers, including many right here on Stack Overflow. –  May 17 '17 at 05:40

1 Answers1

3

To sort by text:

word_list.sort(function (a, b) {
   return a.text.localeCompare(b.text);
});

To sort by weight:

word_list.sort(function (a, b) {
   return a.weight - b.weight;
});
arboreal84
  • 2,086
  • 18
  • 21