Martijn
Martijn

Reputation: 16123

Unwanted sorting of array

I have the following code to get the order of elements. But instead of getting an array in the order of the elements, it's alphabetical.

function gatherTreeIds( $parent ){
    var GatheredIds = [];
    $parent.children('div.nt_row').each(function(){
        GatheredIds[ this.title ] = 'someValue';
    });
    return GatheredIds;
}

<div id="Wrap">
    <div class="nt_row" title="AAA"></div>        
    <div class="nt_row" title="CCC"></div>
    <div class="nt_row" title="BBB"></div>
</div>

Here is my jsFiddle example (check console for result). It gives me ['AAA','BBB','CCC'] instead of the desired ['AAA','CCC','BBB'].

Important! This has to get recursive. It is not at this moment to simplify the problem.

Upvotes: 2

Views: 154

Answers (2)

peterjwest
peterjwest

Reputation: 4452

You're confusing the two concepts of arrays and hashes. Arrays have order, while hashes have named keys, you can't have both in a data single structure.

With an array you would use:

var GatheredIds = [];
$parent.children('div.nt_row').each(function(){
    GatheredIds.push('someValue');
});
return GatheredIds;

If you want to record the item title, you can use an array of hashes:

var GatheredIds = [];
$parent.children('div.nt_row').each(function(){
    GatheredIds.push({value: 'someValue', title: this.title);
});
return GatheredIds;

Upvotes: 4

VisioN
VisioN

Reputation: 145478

This happens because you store titles as object properties. In your example GatheredIds is not array, this is an object.

Objects in JavaScript do not have order (opposite to PHP's map-arrays). If you need to follow the order, you should use arrays instead.

One possible solution:

function gatherTreeIds( $parent ){
    return $parent.children('div.nt_row').map(function() {
        return {
            title: this.title,
            value: 'someValue'
        };
    }).get();
}

DEMO: http://jsfiddle.net/FmyBb/4/

Upvotes: 3

Related Questions