Reputation: 4192
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?
Upvotes: 0
Views: 387
Reputation: 50654
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])
Upvotes: 0
Reputation: 105
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.
Upvotes: 0
Reputation: 326
According to MDN sort()
will modify the original array!
MDN Array.prototype.sort()
Upvotes: 0
Reputation: 2376
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
Upvotes: 0
Reputation: 20039
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])
Upvotes: 2