1

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>

3 Answers 3

5

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

var sortRNums = rNums.slice(0);
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks I thought I must have been close this is now working. I will have to some more reading on slice
2

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);

Comments

2

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?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.