DEV Community

Discussion on: Simplest way to compare two numbers array in JS

Collapse
 
ksengine profile image
Kavindu Santhusa • Edited

Correct Algorithm

Here is the Correct Algorithm

const array1 = [1, 2, 3, 4, 5];
const array2 = [1, 2, 3, 4, 5];

// This is the function
const compare = (a1, a2) =>
  a1.length == a2.length &&
  a1.every(
    (element, index) => element === a2[index]
  );

// Example
console.log(compare(array1, array2));

// Sorted
console.log(compare(array1.sort(), array2.sort()));
Enter fullscreen mode Exit fullscreen mode
Collapse
 
hnicolas profile image
Nicolas Hervé

You forgot to compare array sizes.

compare([1], [1, 2]); // true
Enter fullscreen mode Exit fullscreen mode
Collapse
 
virtualghostmck profile image
virtualghostmck

If a2 has more elements than a1, then this algo fails.

Collapse
 
ksengine profile image
Kavindu Santhusa

Thanks, Now it's upadated.

Collapse
 
0shuvo0 profile image
Shuvo

Yes but we are talking about the simple approach here

Collapse
 
0shuvo0 profile image
Shuvo

And your function has some drawbacks also
algo fail

Collapse
 
darkwiiplayer profile image
𒎏Wii 🏳️‍⚧️

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.

Thread Thread
 
0shuvo0 profile image
Shuvo

agreed 100%

Collapse
 
ksengine profile image
Kavindu Santhusa

In js your Objects are not equal
If your arrays are

const num5 = { num: 5 };
const array1 = [1, 2, 3, 4, num5];
const array2 = [1, 2, 3, 4, num5];
Enter fullscreen mode Exit fullscreen mode

It works.

Collapse
 
ilumin profile image
Teerasak Vichadee

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

Collapse
 
marcosteinke profile image
Marco Steinke

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

getTotalDifference(anotherVector) {
    let diff = 0;
    this.values.forEach((e,i) => { return (this.values[i] != anotherVector[i]) ? diff++ : diff = diff; })
    return diff;
}
Enter fullscreen mode Exit fullscreen mode