0

I have next code what should compare the arrays;

function compare(arr) {
    const sorted = arr.sort((a,b)=> a -b).join(',');
    const unsorted = arr.join(',')
    console.log(sorted === unsorted) // true
}

compare([1, 16, 7])

Why i get true, or the arrays should be different?

4
  • 1
    I'm pretty sure that the sort changes the original array. Commented Apr 5, 2020 at 11:41
  • 1
    Side note: if you want to check if an array is sorted, then there are more efficient way to do this :) Commented Apr 5, 2020 at 11:41
  • @evolutionxbox, i also think this, but why?, or even if inside function i will call console.log(arr), i will have also a sorted array. Commented Apr 5, 2020 at 11:43
  • @AskMen because Array.prototype.sort() is in-place method, means it affects original array it is working on Commented Apr 5, 2020 at 11:59

5 Answers 5

2

Try copying the array using spread opeartor

Note that the array is sorted in place, and no copy is made.

function compare(arr) {
  const sorted = [...arr].sort((a, b) => a - b).join(',');
  const unsorted = arr.join(',')
  console.log(sorted === unsorted) // true
}

compare([1, 16, 7])

Sign up to request clarification or add additional context in comments.

1 Comment

For clarity "sorted in place" means that the original array is modified. array.sort(...) has the same effect as array = array.sort(...), which can lead to accidental setting of the original variable.
0

The reason is that you are comparing the same string. How is it the same string? Well, .sort() sorts in place - meaning it doesn't return a new sorted array but the the same array just gets sorted. So for unsorted you are joining the same sorted array. You can try switch the order of the assignments and the result should be diferent

Comments

0

According to MDN sort() will modify the original array! MDN Array.prototype.sort()

Comments

0

Since you´re sorting an array is it pretty much impossible to check if they are equal or not. If you wan't to check if all values that exists are the same as both arrays could you try something like this.

    function compare(arr) {
    const unsorted = arr.slice()
    const sorted = arr.sort((a,b)=> a -b)

    console.log(sorted)
    console.log(unsorted)

    if(checkIfValuesAreEqual(sorted, unsorted))
        console.log("they are equal")
    else
        console.log("they are not equal")
}

checkIfValuesAreEqual = (sorted, unsorted) => {
    if(sorted.length != unsorted.length)
        return false

    let sortedObj = {}
    let unsortedObj = {}

    for(const value of sorted){
        if(value in sortedObj)
            sortedObj[value] += 1
        else
            sortedObj[value] = 1
    }

    for(const value of unsorted){
        if(value in unsortedObj)
            unsortedObj[value] += 1
        else
            unsortedObj[value] = 1    
    }

    const keysSorted = Object.keys(sortedObj)
    const keysUnSorted = Object.keys(unsortedObj)


    if(keysSorted.length != keysUnSorted.length)
        return false


    for(const key of keysSorted){
        if(sortedObj[key] != unsortedObj[key])
            return false
    }

    return true

}

compare([1, 16, 7])

Had to change some things like unsorted = arr.slice(), Javascript puts everything by reference so unsorted n sorted are the same. To check if both are the same do i need to loop through so i needed them as arrays and not string.

I don't think you can compare two strings if one is sorted and the other is not since some values swap places.

Comments

0

Array#Sort sorts in place. So, Join the array before sorting:

function compare(arr) {
    const unsorted = arr.join(',');//moved up
    const sorted = arr.sort((a,b)=> a -b).join(',');
    console.log(sorted === unsorted) // false
}

compare([1, 16, 7])

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.