Reputation: 120
So I have an JSON object being returned by ajax that I need to sort by a meta value of 1 and 0 first then by title keeping the 1's at the top. So essentially I need to sort everything by custom_fields['visitor_bureau'] then by title. I've tried just about everything I can including searching for different sort functions all over the place to get a better idea of how to write this and can't seem to get it right.
I used JSON.stringify() to make the object a string. This is actually a huge JSON object but I just need the 2 fields to sort by. visitor_bureau is boolean and the title can be any string really. This is a horrible description but I am braindead here.
{"title":"Some Place","visitor_bureau":"1"}
Upvotes: 0
Views: 709
Reputation: 97247
This will work, using the sort()
method:
let array = [{
"title": "A Some Place",
"visitor_bureau": "0"
}, {
"title": "B Some Place",
"visitor_bureau": "1"
}, {
"title": "C Some Place",
"visitor_bureau": "1"
}];
array.sort((a, b) => b.visitor_bureau - a.visitor_bureau || a.title.localeCompare(b.title));
console.log(array)
Upvotes: 4