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' },
];
user this where 'count'-> first priority and 'year'-> second priority
Based on great @RobG solution, this is a generic function to sort by multiple different properties, using a JS2015 tricky on
map + find
:Also, if you prefer, a traditional JS version (use with caution due to find compatibility in old browsers):
You can use JavaScript's
.sort()
array method (try it out):Note: This changes the original array. If you need to make a copy first, you can do so:
If you are looking to sort strings in alphabetical order rather than numbers, here's a sample problem and its solution.
Example Problem: Array of arrays (finalArray) with first entry a folder path and second entry the file name; sort so that array is arranged by folder first, and within identical folders, by file name.
E.g. after sorting you expect:
Refer to Array.prototype.sort() - compareFunction
Keep in mind, "Z" comes before "a" (capitals first according to Unicode code point) which is why I have toLowerCase(). The problem the above implementation does not solve is that "10abc" will come before "9abc".
you have to work out this problem like this way
};
e.g : data.sort(customSort('year', customSort('count')));
(See the jsfiddle)