I have an array of JSON objects I need to sort. The array needs to be sorted by two different properties. First, the array should be alphabetically sorted by the found property. Second, the array should be sorted so that the website property descends in the same order specified in siteOrder.
var siteOrder = ['facebook', 'twitter', 'reddit', 'youtube', 'instagram'];
var data = [
{found: 'booker', website: 'reddit'},
{found: 'john', website: 'facebook'},
{found: 'walter', website: 'twitter'},
{found: 'smith', website: 'instagram'},
{found: 'steve', website: 'youtube'},
{found: 'smith', website: 'facebook'},
{found: 'steve', website: 'twitter'},
{found: 'john', website: 'instagram'},
{found: 'walter', website: 'youtube'}
];
/* Example output: Sorted output by found, respecting the order of the websites specified
{found: 'booker', website: 'reddit'},
{found: 'john', website: 'facebook'},
{found: 'john', website: 'instagram'},
{found: 'smith', website: 'facebook'},
{found: 'smith', website: 'instagram'},
{found: 'steve', website: 'twitter'},
{found: 'steve', website: 'youtube'},
{found: 'walter', website: 'twitter'},
{found: 'walter', website: 'youtube'}
*/
I can alphabetically sort the by the found property using:
data.sort(function(a, b) {
var textA = a.found.toUpperCase();
var textB = b.found.toUpperCase();
return (textA < textB) ? -1 : (textA > textB) ? 1 : 0;
});
However I do not know how to make it also respect the specified order of the websites.