简体   繁体   中英

Why does the sort() function changes values of numbers in this Array?

var _txtString = ":un:-:un:-:deux:-:deux:-:deux:-:trois:-:trois:" ;
var _array = ["un", "deux", "trois"]  ;
var _items = new Array();

for (var t =0; t < _array.length; t++) {
    found = _txtString.match(new RegExp(':' + _array[t]+ ':', 'g'));
    _items[t] = parseInt(found.length);
    //_items.sort();
    document.write("<br />" + _items[t] + "  " + _array[t]);
}

Hi, when I run this code, results displayed are properly counted:

2 un
3 deux
2 trois

But when I uncomment the sort() line, count is wrong:

2 un
3 deux
3 trois <=

What I wanted is to sort the result returned by numeric value. What is beyound my understanding is that the sort() function changes the actual value ?! Any clue why ?

Thanks

Because you are sorting, you are changing the order of the array. So when you sort the "3" becomes the last index and it writes that out.

_items[t] = parseInt(found.length);  //[2,3,2]
_items.sort();  //[2,2,3]
document.write("<br />" + _items[t] + "  " + _array[t]);  //here you are reading the last index which is 3

If you want to sort by the count, you need to do it after you calculate everything.

Basic idea:

var _txtString = ":un:-:un:-:deux:-:deux:-:deux:-:trois:-:trois:";
var _array = ["un", "deux", "trois"];
var _items = new Array();

for (var t = 0; t < _array.length; t++) {
    found = _txtString.match(new RegExp(':' + _array[t] + ':', 'g'));
    _items.push({
        count: found.length,
        text: _array[t]
    });
}

_items.sort(function (a, b) {
    return a.count - b.count;
});

for (var i = 0; i < _items.length; i++) {
    console.log(_items[i].count, _items[i].text);
}

The sort command in javascript does an in-place sort, meaning it will mutate your array order. When this occurs it simply looks to me like your code is just out of sync to what you are expecting.

There is no way to avoid this unless you make a copy of the array and do a sort on the copy therefore leaving the original array as-is.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM