I think that this will ONLY work if array1 and array2 are each arrays of string variables, it won't work for arbitrary array types.
Furthermore, those strings cannot be arbitrary. Specifically they cannot contain white-space (array element "some thing" would not work but "something" would be OK).
I have annotated the code below to explain it. Whoever wrote it should be a little ashamed for not providing some explanatory comments, not least a function header to explain the required argument types. A try-catch block wouldn't have gone amiss either.
Anyway here goes:
function unique (array1, array2) {
var obj1 = {};
for (var i = array1.length-1; i >= 0; -- i)
obj1[array1[i]] = array1[i];
for (var i = array2.length-1; i >= 0; -- i)
obj1[array2[i]] = array2[i];
var result = []
for (var k in obj1) {
result +=(obj1[k]);
}
return result;
}
The declaration of obj1 follows
Javascript best practice for the declaration of a new object.
The key to understanding the above code is the following:
Consider a Javascript object, myObj, containing properties such as "prop1", "prop2" etc. You are probably familiar with accessing those objects using this notation:
var prop1Val = myObj.prop1;
var prop2Val = myObj.prop2;
However, you can also access those properties using this notation:
var prop1Val = myObj["prop1"];
var prop2val = myObj["prop2"];
Hopefully you can now see why I said at the start that array1,2 must only contain simple strings that don't contain white-space. If they did you'd be trying to do something like this:
var prop1Val = myObj["some thing"];
Which as you now know would correspond, in the more familiar notation, to:
var prop1Val = myObj.some thing;
Anyone whoever doubted the beauty of Javascript can't truly know the language. These kind of constructs - although they can be confusing - are exceptionally powerful. It's a language that was well ahead of its time!