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.
asked Aug 3, 2016 at 19:13
3 Answers 3
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.
answered Aug 3, 2016 at 19:18
Comments
This is also can be done like this
a.toString() === b.toString()
answered Aug 3, 2016 at 19:23
2 Comments
Park Taecyeon
This works, unfortunately, I'm dealing with 20 MB JSON files and it's taking a long time.
Jorawar Singh
@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 :-)
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,84020 gold badges67 silver badges92 bronze badges
answered Aug 3, 2016 at 19:16
1 Comment
dandavis
only type-safe solution presented so far.
lang-js
a
andd
are the same, butvar e = [5,4,3,2,1];
would be different, because the same content is in a different order?