Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: Compare three arrays

I want to compare many arrays and combine any that are identical:

A = [1,2,3];
B = [1,2,3];
C = [1,2,3];

D = [10,11,12];
E = [10,11,12];
F = [10,11,12];

G = [13,14];
H = [13,14];

If there are identical arrays then I'd like to create new arrays out of the identical ones:

I = [1,2,3];
J = [10,11,12];
K = [13,14];

Would I need to iterate through each element in one array against ALL of the elements in the other arrays?

for (var i in A) {
    for (var j in B) {
        if (A[i] == J[j]) {
            // create new arrays
        }
    }
}

etc...

Then, create new arrays out of the matches? Sounds like a lot of overhead.

What's the best way to accomplish this?

Thanks!

like image 772
JsusSalv Avatar asked Oct 07 '11 23:10

JsusSalv


People also ask

How do you compare three values in an array?

To compare 3 values, use the logical AND (&&) operator to chain multiple conditions. When using the logical AND (&&) operator, all conditions have to return a truthy value for the if block to run. Copied! In the code example, we used the logical AND (&&) operator to chain two conditions.

Can you compare arrays JavaScript?

While JavaScript does not have an inbuilt method to directly compare two arrays, it does have inbuilt methods to compare two strings. Strings can also be compared using the equality operator. Therefore, we can convert the arrays to strings, using the Array join() method, and then check if the strings are equal.

Why can't JavaScript compare arrays?

That would be great! But unfortunately, it can't be done because arrays are actually objects in javascript. Primitive types can be compared by their value in javascript, like strings and integers. However objects are more complex types and are compared by their reference, or place they are stored in memory.


1 Answers

If you're just trying to finish up with the unique arrays, I would use a hash approach:

var myArrays = [A,B,C,D,E,F,G],
    uniques = [],
    hashes = {};

for (var i=0; i < myArrays.length; i++) {
    var hash = JSON.stringify(myArrays[i]); // or .toString(), or whatever
    if (!(hash in hashes)) {
        hashes[hash] = true;
        uniques.push(myArrays[i]);
    }
}
// uniques now holds all unique arrays
like image 185
nrabinowitz Avatar answered Sep 29 '22 07:09

nrabinowitz