Jump to content

comparing arrays


jimfog

Recommended Posts

Suppose we have two arrays...

The one has 2 elements the other 1.

They also have one common element...they might both contain 5 for example.

 

My problem is that I want to find the identity of the element that is not common....that 2nd element in the array that has 2 elements.

 

How I could possibly achieve this?

Link to comment
Share on other sites

Use array_diff to get the difference between the arrays.

That is PHP method...I am looking for something in javascript.

Link to comment
Share on other sites

Ah, I didn't notice. The most obvious way would be to just loop through both of them to check if each element is in the other array, and build a third array of elements that either are or aren't present. That is what a diff function would do. Other than that, you could get clever with something like the filter method.

Link to comment
Share on other sites

There is a really good utility library (if you feel so inclined) called lodash that you may want to look into

https://lodash.com/

 

it has a lot of useful object and array decorator functions, such as difference

https://lodash.com/docs#difference

 

or if you are using jquery, there seems to be a neat solution here using grep

http://stackoverflow.com/questions/10927722/jquery-compare-2-arrays-return-difference

  • Like 1
Link to comment
Share on other sites

I decide to use something like this-take from the stackOverflow post mentioned above:

$(array1).not(array).get();

I have the following problem now....the above code gives us an array element or more.

If is PUSH this/these to another array I will have a multidimensional array...here is the code:

          var array1=['5','6'];          var array2=['5']          var remove=['remove'];          var remserv=$(array1).not(array2).get();//this will give us an array containing 6          remove.push(remserv);

How am I going prevent creating a multidimensional array.

I want 6 PUSHED in the remove array as an element and not as another array containing 6.

Link to comment
Share on other sites

thanks...

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...