Is it possible to get the difference of an associative array and a regular array in JavaScript?
Example
array1 = [5, 1, 3];
array2 = [1 => 15, 2 => 20, 3 => 10, 4 => 5, 5 =>50 ];
The difference would be...
diff = [2 => 20, 4=> 5];
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:
array1 = [5, 1, 3];
array2 = {1: 15, 2: 20, 3: 10, 4: 5, 5: 50};
var result = {};
for (var i in array2) {
if (array1.indexOf(+i) < 0) {
result[i] = array2[i];
}
}
alert(JSON.stringify(result));
My hack is the +i
in the indexOf
call, because the properties of your "associative array" are strings, but your array1
contains 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, indexOf
is an ES5 method, so if your JavaScript engine is ES3 or below, you will need to implement indexOf
on your own. An example of how to do this is at MDN. Alternatively, you can just do the equivalent of indexOf
by searching the array on your own.