Array#sort
:
The sort is not necessarily stable.
And while you sort only by the name part, up to the first space, the sorting algorithm choose a place for same name, which do not respect the numerical value.
To overcome this problem, you could sort by the numerical value as well.
Any sorting before the last sorting is altered.
You need for strings which have more than one space a different method, because you get with two spaces three elements. Now it uses not numerical values at start and the numerical value at the end of the string.
var animals_order = 'Funny Pig, Angry Lion, Little Rabbit',
data = [{ result: [{ name: "Angry Lion 2" }, { name: "Funny Pig 1" }, { name: "Funny Pig 2" }, { name: "Angry Lion 1" }, { name: "Funny Pig 3" }, { name: "Little Rabbit 2" }, { name: "Little Rabbit 1" }] }];
function order () {
data.forEach(item => {
item.result.sort((a, b) => {
var [aName, aValue] = a.name.split(/\s(?=\d)/),
[bName, bValue] = b.name.split(/\s(?=\d)/);
return animals_order.indexOf(aName) - animals_order.indexOf(bName) || aValue - bValue;
});
});
}
function display() {
data[0].result.forEach(assignment => {
document.getElementById('divID').innerHTML += "<br />" + assignment.name;
});
}
order();
display();
<div id="divID"></div>