First of all, let's fix your removedDupes
function by adding intArray
as an argument and declaring the loop iterators as local variables var x
:
function removeDupes(intArray) {
var out = [],
obj = {};
for (var x = 0; x < intArray.length; x++) {
obj[intArray[x]] = 1;
}
for (var x in obj) {
out.push(x);
}
return out;
}
The first loop iterates over all intArray
elements. For each element it creates a new property on obj
with key intArray[x]
and value 1
via obj[intArray[x]] = 1
. This is called bracket notation. Now, objects can't have duplicate keys. So adding the same property key twice actually overrides the previously added property. Thus, when the loop completes, your obj
has exactly one key per unique array element.
The second loop then pushes these keys into the resulting out
array.
There are some issues with your removeDupes
function. Firstly, it returns an array of string
elements even though the input is an array of number
elements. This is because obj
keys can't be numbers and are always converted to strings. You can fix it by storing the numeric values along with the keys as follows:
function removeDupes(intArray) {
var out = [],
obj = {};
for (var x = 0; x < intArray.length; x++) {
obj[intArray[x]] = intArray[x];
}
for (var x in obj) {
out.push(obj[x]);
}
return out;
}
Now, this works, but it is very verbose. You can make it shorter by replacing the second loop with return Object.values(obj);
. Or even shorter by using a Set
:
function removeDupes(intArray) {
return [...new Set(intArray)];
}