Home > Blockchain >  javascript: array sort data become weird
javascript: array sort data become weird

Time:09-17

previously i've do some technical test with hackerrank. For the simple testing i need to make two different array so i can check it the difference both of them. the first array will be unsorted, and the second will be sorted.

Here's my code:

function dataSort(thedata) {
    // Write your code here
    var unsorted = thedata
    var sorted = thedata
    console.log("not sorted", unsorted) // first log
    for(let i = 0; i < sorted.length; i  )
    {
        for(let j = i; j < sorted.length; j  )
        {
            if(sorted[i] > sorted[j])
            {
                let temp = sorted[i]
                sorted[i] = sorted[j]
                sorted[j] = temp
                
            }
        }
    }
    console.log("sorted",sorted) // second log
}
dataSort([1,3,4,2,1])

above code given the result below

not sorted [ 1, 3, 4, 2, 1 ]
sorted [ 1, 1, 2, 3, 4 ]

Okay, that's seems have no problem. but when i move the first console after the bubble sort near with second console, the data also sorted

function dataSort(thedata) {
    // Write your code here
    var unsorted = thedata
    var sorted = thedata
    for(let i = 0; i < sorted.length; i  )
    {
        for(let j = i; j < sorted.length; j  )
        {
            if(sorted[i] > sorted[j])
            {
                let temp = sorted[i]
                sorted[i] = sorted[j]
                sorted[j] = temp
                
            }
        }
    }
    console.log("not sorted", unsorted) // first log
    console.log("sorted",sorted) // second log
}
dataSort([1,3,4,2,1])

result

not sorted [ 1, 1, 2, 3, 4 ]
sorted [ 1, 1, 2, 3, 4 ]

Can you tell me what happened?

CodePudding user response:

GrafiCode gave you the correct explanation about why this happens.

Here is a possible solution:

function dataSort(thedata) {
    // Write your code here
    var unsorted = new Array(...thedata)
    var sorted = new Array(...thedata)
    for(let i = 0; i < sorted.length; i  )
    {
        for(let j = i; j < sorted.length; j  )
        {
            if(sorted[i] > sorted[j])
            {
                let temp = sorted[i]
                sorted[i] = sorted[j]
                sorted[j] = temp
                
            }
        }
    }
    console.log("not sorted", unsorted) // first log
    console.log("sorted",sorted) // second log
}
dataSort([1,3,4,2,1])

I hope it helps you :)

  • Related