0

I have this array and I want to sort it by the "Category" field. How can I do it?

[ 
  { amount: 3200, vendor: "Elevation", category: "Salary" },
  { amount: -7, vendor: "Runescape", category: "Entertainment" },
  { amount: -20, vendor: "Subway", category: "Food" },
  { amount: -98, vendor: "La Baguetterie", category: "Food" }
]
falcon25
  • 11
  • 6

1 Answers1

3

    arr = [ 
        { amount: 3200, vendor: "Elevation", category: "Salary" },
        { amount: -7, vendor: "Runescape", category: "Entertainment" },
        { amount: -20, vendor: "Subway", category: "Food" },
        { amount: -98, vendor: "La Baguetterie", category: "Food" }
    ];

    arr.sort(function(a, b) {
        if (a.category < b.category) {
            return -1;
        } else if (a.category > b.category) {
            return 1;
        } else {
            return 0;
        }
    });

    console.log(arr);
jspcal
  • 50,847
  • 7
  • 72
  • 76