简体   繁体   中英

Finding unique arrays in the most efficient method

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? Ie array a, b and c are distinct, where the order matters.

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]; 
});

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.

这也可以这样做

a.toString() === b.toString()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM