jquery - Sorting objects in an array -


ok got array of objects in array. associative arrays. array of associative arrays.

console log outputs this:

[array object] [object{...},object{...},object{...}, etc...] 

each object has name, price , color. want sort them alphabetical order , ascending or descending in price.

i've got jquery code put them onto page, need insert bit of code put them in order choose. ideas?

you can use javascript array sort method accepts compare function parameter.

var = [{name: 'a', price: 1, color: 'red'}, {name: 'b', price: 2, color: 'red'}, {name: 'c', price: 3, color: 'blue'}]; // ascending order a.sort(function (a, b) {     return a.price - b.price; }); // descending order a.sort(function (a, b) {     return b.price - a.price; }); 

edit: if need sort first name in ascending order , price in ascending or descending order then:

// sort name in ascending order first , price in ascending order a.sort(function (a, b) {     return a.name.localecompare(b.name) || a.price - b.price; }); // sort name in ascending order first , price in descending order a.sort(function (a, b) {     return a.name.localecompare(b.name) || b.price - a.price; }); 

Comments

Popular posts from this blog

Python Kivy ListView: How to delete selected ListItemButton? -

asp.net mvc 4 - A specified Include path is not valid. The EntityType '' does not declare a navigation property with the name '' -