0

I faced with really strange thing (at least it is strange to me). I am trying to sort items in array but receiving really different result in Chrome and Safari.

Please take a look at my JSFIDDLE in CHROME and then in Safari

Chrome has the right order, which should be:

Funny Pig 1 

Funny Pig 2 

Funny Pig 3 

Angry Lion 1

Angry Lion 2

Little  Rabbit 1

Little Rabbit 2

Any thoughts?

Maximus Dredoff
  • 306
  • 3
  • 17
  • 1
    thoughts: safari is the new internet explorer - – Jaromanda X Apr 18 '18 at 12:33
  • 1
    does safari (I don't safari at all) like it better if you `item.result.sort((a, b) => { return animals_order.indexOf(a.name.split(' ')[0]) > animals_order.indexOf(b.name.split(' ')[0]) ? 1 : (animals_order.indexOf(a.name.split(' ')[0]) < animals_order.indexOf(b.name.split(' ')[0]) ? -1 : 0); });` – Jaromanda X Apr 18 '18 at 12:36
  • @JaromandaX yes, it works now. In Chrome and Safari. Thank you! – Maximus Dredoff Apr 18 '18 at 12:52

1 Answers1

3

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>
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392