Sample codes
These sample codes show how to sort an array of objects by multiple criteria using a single sort() and multiple sort() call.
Example dataset
data = [
{ acctent: "Entity B", acct: "1001", year: 2024 },
{ acctent: "Entity A", acct: "1002", year: 2023 },
{ acctent: "Entity B", acct: "1000", year: 2024 },
{ acctent: "Entity C", acct: "1005", year: 2022 },
{ acctent: "Entity A", acct: "1001", year: 2025 },
{ acctent: "Entity B", acct: "1001", year: 2023 },
{ acctent: "Entity A", acct: "1001", year: 2024 },
{ acctent: "Entity C", acct: "1005", year: 2022 }
]
Single sort() call
This code uses the recommended single sort() call with a compound comparison function to sort by all fields in order of priority.
data.sort(function(a, b)
{
var akey1 = a["acctent"];
var bkey1 = b["acctent"];
if (akey1 > bkey1)
{
return 1;
}
else if (akey1 < bkey1)
{
return -1;
}
else // acctent is the same, sort by acct
{
var akey2 = a["acct"];
var bkey2 = b["acct"];
if (akey2 > bkey2)
{
return 1;
}
else if (akey2 < bkey2)
{
return -1;
}
else // acct is also the same, sort by year
{
var akey3 = a["year"];
var bkey3 = b["year"];
if (akey3 > bkey3)
{
return 1;
}
else if (akey3 < bkey3)
{
return -1;
}
else // All keys are the same
{
return 0;
}
}
}
})
Multiple sort() call
This code sorts the array multiple times, starting with the least important field, which increases overall processing time.
data.sort(function(a, b)
{
if (a.year < b.year)
{
return -1;
}
if (a.year > b.year)
{
return 1;
}
return 0;
})
data.sort(function(a, b)
{
if (a.acct < b.acct)
{
return -1;
}
if (a.acct > b.acct)
{
return 1;
}
return 0;
})
data.sort(function(a, b)
{
if (a.acctent < b.acctent)
{
return -1;
}
if (a.acctent > b.acctent)
{
return 1;
}
return 0;
})