Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort by two values prioritizing on one of them

How would I sort this data by count and year values in ascending order prioritizing on the count value?

//sort this var data = [     { count: '12', year: '1956' },     { count: '1', year: '1971' },     { count: '33', year: '1989' },     { count: '33', year: '1988' } ]; //to get this var data = [     { count: '1', year: '1971' },     { count: '12', year: '1956' },     { count: '33', year: '1988' },     { count: '33', year: '1989' }, ]; 
like image 362
Dojie Avatar asked Jan 02 '11 01:01

Dojie


People also ask

How do I sort alphabetically in JavaScript?

JavaScript Array sort() The sort() sorts the elements of an array. The sort() overwrites the original array. The sort() sorts the elements as strings in alphabetical and ascending order.


1 Answers

(See the jsfiddle)

var data = [     { count: '12', year: '1956' },     { count: '1', year: '1971' },     { count: '33', year: '1989' },     { count: '33', year: '1988' } ];  console.log(data.sort(function (x, y) {     var n = x.count - y.count;     if (n !== 0) {         return n;     }      return x.year - y.year; }));
like image 162
cdhowie Avatar answered Sep 22 '22 12:09

cdhowie