Is it possible to get the difference of an associative array and a regular array in Javascript?
Ex.
array1 = [5, 1, 3];
array2 = [1 => 15, 2 => 20, 3 => 10, 4 => 5, 5 =>50 ];
The difference would be…
diff = [2 => 20, 4=> 5];
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
I assume your question just had a small typo in your declaration of
array2. This is not a big deal.Anyway, here is a bit of hack, but it gives you what you want:
Working example
My hack is the
+iin theindexOfcall, because the properties of your “associative array” are strings, but yourarray1contains numbers. The unary+produces a number from a string. Kind of hackish but it is idiomatic an accepted JavaScript practice.ADDENDUM
As RobG points out,
indexOfis an ES5 method, so if your JavaScript engine is ES3 or below, you will need to implementindexOfon your own. An example of how to do this is at MDN. Alternatively, you can just do the equivalent ofindexOfby searching the array on your own.