1

I have the following arrays,

var a = [1,2,3,4,5];
var b = [2,3,4,5,6];
var c = [4,5,6,7,8];
var d = [1,2,3,4,5];

What is the most efficient way to find out the arrays that are distinct? I.e array a, b and c are distinct, where the order matters.

  • Where you say _"the order matters"_ do you mean that `a` and `d` are the same, but `var e = [5,4,3,2,1];` would be different, because the same content is in a different order? – Stephen P Aug 03 '16 at 19:21
  • try this very easy a.toString() === b.toString() – Jorawar Singh Aug 03 '16 at 19:26
  • probably interesting: http://stackoverflow.com/questions/3115982/how-to-check-if-two-arrays-are-equal-with-javascript – Hitmands Aug 03 '16 at 19:26
  • The solutions below are valid, a more efficient one would be to do something similar to bucket sort, but doubt you need that much efficiency – juvian Aug 03 '16 at 19:35

3 Answers3

1

You can use Array.prototype.every() to compare arrays with Javascript

var a = [1,2,3,4,5];
var b = [2,3,4,5,6];

var is_same = (a.length == b.length) && a.every(function(element, index) {
return element === b[index]; 
});
Graham
  • 7,431
  • 18
  • 59
  • 84
CMedina
  • 4,034
  • 3
  • 24
  • 39
1

One interesting way would be to convert them to String and Compare them. You could JSON stringify them or just join them like this

a.join('') === b.join('')

This works just because you say the order matters. I don't know the benchmarks between using JSON's stringify over join primitive. Maybe you could try that.

cipher
  • 2,414
  • 4
  • 30
  • 54
1

This is also can be done like this

a.toString() === b.toString()
Jorawar Singh
  • 7,463
  • 4
  • 26
  • 39
  • This works, unfortunately, I'm dealing with 20 MB JSON files and it's taking a long time. – Park Taecyeon Aug 14 '16 at 16:11
  • @ParkTaecyeon that's something hard to do anything about then finding a way to make file shorter, it's not a good idea in best practice having a json file of 20 MB. please accept the answer if you find it useful :-) – Jorawar Singh Aug 14 '16 at 17:30