ak85
ak85

Reputation: 4264

js output unsorted array

I have the below code which is also in this fiddle.
I have listed the output and the expected output below. I can't understand why I haven't sorted the rNums yet it still outputs the sorterd results?

If I comment out the sort function then random appears as I want but not ordered. What am I doing wrong here?

Random should be displaying as it is in nNums and ordered should be displayed in numerical order?

    <ul id="random"></ul>
    <ul id="ordered"></ul>

    <script>
    var rNums = [1,5,3,2,4];
    console.log(rNums);
    var sortRNums = rNums;

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

    $.each(rNums, function (index, value) {
        $("#random").append('<li>' + value + '</li>');
    });

    $.each(sortRNums, function (index, value) {
        $("#ordered").append('<li>' + value + '</li>');
    });
    console.log(sortRNums);
    </script>

Output

    <ul id="random">
            <li>1</li>
            <li>2</li>
            <li>3</li>
            <li>4</li>
            <li>5</li>
    </ul>

    <ul id="ordered">
            <li>1</li>
            <li>2</li>
            <li>3</li>
            <li>4</li>
            <li>5</li>
    </ul>

Expected Output

    <ul id="random">
            <li>1</li>
            <li>5</li>
            <li>3</li>
            <li>2</li>
            <li>4</li>
    </ul>

    <ul id="ordered">
            <li>1</li>
            <li>2</li>
            <li>3</li>
            <li>4</li>
            <li>5</li>
    </ul>

Upvotes: 1

Views: 1407

Answers (3)

treeno
treeno

Reputation: 2600

The Problem is, that

var sortRNums = rNums;

does not copy the array. sortRNums and rNums point to the same array.

Just take a look at this thread for more information: How do you clone an Array of Objects in Javascript?

Upvotes: 2

Matas Vaitkevicius
Matas Vaitkevicius

Reputation: 61459

It's is because variable sortNums is pointing to same memory location JsFiddle

var rNums = [1,5,3,2,4];
var rUnsortedNums = $.map(rNums, function(i){return i;});
console.log(rNums);
var sortRNums = rNums;

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

$.each(rUnsortedNums, function (index, value) {
    $("#random").append('<li>' + value + '</li>');
});

$.each(sortRNums, function (index, value) {
    $("#ordered").append('<li>' + value + '</li>');
});
console.log(sortRNums);

Upvotes: 2

Yury Tarabanko
Yury Tarabanko

Reputation: 45106

sort modifies original array you need to create a copy before sorting.

var sortRNums = rNums.slice(0);

Upvotes: 5

Related Questions