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.

asked Aug 3, 2016 at 19:13
4
  • 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? Commented Aug 3, 2016 at 19:21
  • try this very easy a.toString() === b.toString() Commented Aug 3, 2016 at 19:26
  • probably interesting: stackoverflow.com/questions/3115982/… Commented Aug 3, 2016 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 Commented Aug 3, 2016 at 19:35

3 Answers 3

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.

answered Aug 3, 2016 at 19:18

Comments

1

This is also can be done like this

a.toString() === b.toString()
answered Aug 3, 2016 at 19:23

2 Comments

This works, unfortunately, I'm dealing with 20 MB JSON files and it's taking a long time.
@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 :-)
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,84020 gold badges67 silver badges92 bronze badges
answered Aug 3, 2016 at 19:16

1 Comment

only type-safe solution presented so far.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.