In case of string we can simply use == or === to see if they are same but we can't use those to see in two arrays are similar or in other words they have same elements.
So this wont work.
const array1 = [1, 2, 3, 4, 5]
const array2 = [1, 2, 3, 4, 5]
console.log(array1 == array2) //false
But what if we convert our array to string? Then you can use the comparison operator. This makes the task very easy. We can sort an array using toString method eg. array1.toString()
or we can use this hack
console.log([1, 2, 3, 4, 5] + "")
//logs 1,2,3,4,5
console.log(typeof ([1, 2, 3, 4, 5] + ""))
//logs string
So basically if we try to concatenate string(empty string in this case) to an array the array will be converted to a string.
so now we can simply use the arrays as strings and compare them
const array1 = [1, 2, 3, 4, 5]
const array2 = [1, 2, 3, 4, 5]
console.log(array1 + "" == array2 + "") //true
Also if you want it to work with arrays where the elements are not in order you can first sort them. Let's create a utility function for that
function compareArr(arr1, arr2){
arr1.sort()
arr2.sort()
return arr1 + "" == arr2 + ""
}
const array1 = [1, 2, 3, 4, 5]
const array2 = [1, 5, 2, 4, 3]
console.log(compareArr(array1, array2)) // returns true
Oldest comments (52)
This method will not work for non-primitive values:
Although slight alteration to the algorithm will do the trick:
However even the latter comparison is aimed for simple and small arrays as it can be pretty expensive and yield unexpected results for some edge-cases, e.g.:
In those cases one can use
deep equal
implementation from a variety of packages.true, most short hacks usually have drawbacks
Your solution has too many drawbacks.
That was not very constructive really. Care to explain a bit what the drawbacks could be?
Last time I needed to compare sommeting in JS I used "JSON.stringify" but its still a hack. What is the correct way to do it nowadays? 🤔
Writing an algorithm with loop and recursion if needed
Extractly
There is no general right or wrong as it depends on a particular use case, but if you want an optimal solution that would handle most of the cases it'll probably be a recursive iterator over indices with early return.
I read that as "non-prime values" at first and was severely confused 😆
also you can use lodash.isMatch
_.isMatch
What's the advantage of using the "hack" over the more straightforward way of adding .toString? The advantage of .toString is that it makes your intent more clear, which might be a tiny bit more maintenance friendly
There are two types of people in this world.
Haha, fair enough, but type-1 people then better keep working in 1-person teams
Yes in corporate/serious project you have some rules to follow
I won't consider that a "hack" because as a Java developer I always write
+""
instead oftoString()
, but I would consider stringifying the arrays and comparing them a hack for array comparison.Owh nice to know
Correct Algorithm
Here is the Correct Algorithm
Yes but we are talking about the simple approach here
And your function has some drawbacks also
Whether that's a drawback or by design is questionable; whether two identical objects should be treated as actually the same completely depends on your problem domain.
agreed 100%
In js your Objects are not equal
If your arrays are
It works.
I think it would be greate if we sort the array inside compare function, so we can sure that it will compare with the right position
You forgot to compare array sizes.
This was the solution for a subtask of a problem I recently solved in a project.
I compared two vectors element-wise and counted the amount of distinct elements
If a2 has more elements than a1, then this algo fails.
Thanks, Now it's upadated.
This is so wrong...
didn't saw that coming
actually I was aiming for numbers array. I updated the title
Thanks
Changing built-in Objects is a bad idea.
It is a bad practice, but in the browser context you should be aware that object prototype pollution exists.
A faster way of unsorted equality would be:
It don"t work with duplicated values.
You should remove duplicated items with Set class first before comparing, for example:
const uniqueArr = [... new Set(yourArr)]
but if we compare [1,'2',3] and [1,2,3]; I expect false, and result is true
yes that's why in the post title I said numbers array
I don't think that's a good practice, only because two arrays may contain the same thing but not in the same order... I would tend to just iterate on one and do a comparison with each of the values
If order matters, don't sort them before converting to strings. Yeah of course you could loop them, or use utility libraries.
Check the length first. That is the simplest way to tell they may not be equivalent. You have also just sorted the original array1 and array2. ‘[…array2].sort()’ would be better.
array1.length === array2.length && array1.some???
// Is better for your task
There is one amazing Library called underscore to object comparison
let x=['1',2,5,6];
let y= [1,2,5,6];
let xlenx = x.length;
for(let i=0;i<xlenx;i++){
if(x[i]==y[i]){
console.log(x[i] + ' == ' + y[i])
}
else if(x[i]!==y[i]){
console.log('not same');
break;
}}
Your function mutates the arrays. After calling compareArr(), array2 will have been sorted. You should copy the arrays before sorting so you don't mutate the parameters
Please don't ever do this in production code.
Agreed
So you agree that your own post is a bad idea? 🤔
yes there is always drawbacks of easy hacks.
But if you're confident about your input you might as well ues this
Sometimes hacks make it into production code and become technical debt. This is not a hack that should ever be in a real application.
There are a lot of beginners on DEV and when they see posts like this it teaches them really bad practices. Particularly here since you have tagged it with #beginners.
Besides, your "solution" is for comparing arrays of numbers only. Comparing two arrays containing just numbers is easy with a simple loop since there aren't nested properties, etc.
You could also use
Array.prototype.every
for a one-liner:With both of the above approaches, it bails out as soon as it finds two array elements that are not unique. Stringifying and comparing strings (yuck) requires processing each array in full.
Ahh! I love the smell of a lively Javascript debate thread in the morning, now to peruse (creep) on all the comments whilst remaining quiet as a church mouse. 😅😁😶
I also should've done that