Sagon nicolas
Sagon nicolas

Reputation: 318

Javascript array sorting change index

Hy,

When i sort my array, it change my index :

Myarray.sort(function (a, b) {
    //sort : http://www.javascriptkit.com/javatutors/arraysort2.shtml
    var nameA = a.name.toLowerCase(), nameB = b.name.toLowerCase()
    if (nameA < nameB) //sort string ascending
        return -1;
    if (nameA > nameB)
        return 1;
    return 0; //default return value (no sorting)
});

before my sort :

array : "86", "85", "89"

after my sort :

array : "0", "1", "2"

I want to know if it's normal.

And if it's normal how i can change that ?

Thanks, for your answers.

Upvotes: 1

Views: 3578

Answers (2)

Bergi
Bergi

Reputation: 665344

before my sort, array : "86", "85", "89"

Looks like you have a sparse array: An array of length 90 with items at the indices 85, 86 and 89.

after my sort, array : "0", "1", "2". Is this normal?

Yes. Non-existent properties (0-84, 87, 88) are ignored by sort. From the spec:

NOTE 1: Because non-existent property values always compare greater than undefined property values, and undefined always compares greater than any other value, undefined property values always sort to the end of the result, followed by non-existent property values.

how i can change that ?

You cannot. However, there's no reason to have anything else than that, as you wanted to sort your array, which means reordering the items. Array indices are no ids. If your objects should have ids, make them properties:

var myArray = [
    {"id":"86", "target_area": {"name_area": "Loic"}},
    {"id":"85", "target_area": {"name_area": "aaaaaaaa"}},
    {"id":"81", "target_area": {"name_area": "zzzzzzzzzz"}}
];

Of course, there are workarounds like copying the values to a different array, sorting that and moving them back into the sparse array - see javascript sort sparse array keep indexes. You don't seem to need that, though.

Upvotes: 1

Matt
Matt

Reputation: 3120

Your code is behaving as expected. The sort function will always sort the array starting at 0. When it finds elements (or occupied indices), it will recursively shift it's index to the front of the array until it matches another element which has a higher value.

If you want to retain the indices, you need to create a function which 'stores' the indices previously occupied.

I've created a jsFiddle which does this.

Function

function sortToIndices(arr){
    var occupiedIndices = [],
        objectCollection = [];

    for(var i = 0; i < arr.length; i++) {
        if(arr[i] != null){ // You may want to make this condition more strict
            occupiedIndices.push(i);
            objectCollection.push(arr[i]);
        }
    };

    objectCollection.sort(function(a, b) {
        var nameA = a.target_area.name_area.toLowerCase(), 
            nameB = b.target_area.name_area.toLowerCase();
            if (nameA < nameB) //sort string ascending
                return -1;
            if (nameA > nameB)
                return 1;
            return 0; //default return value (no sorting)
    });

    for (i = 0; i < occupiedIndices.length; i++) {
        arr[occupiedIndices[i]] = objectCollection[i];
    };       
}

Upvotes: 1

Related Questions