would appreciate if anyone could tell me why this isn’t working?
function(array){
var uniqueArray = [];
for (i=0 ; i < array.length; i++) {
for (j=0; j < uniqueArray.length; j++){
if (array[i]===uniqueArray[j]) {
} else {
uniqueArray.push(array[i]);
}
}
}
return uniqueArray;
}
I’ve seen something online about using two more variables:The count and start variables
But I don’t understand why those are necessary. As far as I can tell, mine does the same thing? Nothing if i=j and .push if it doesn’t.
3
Answers
Your code can’t work because, as noticed by @pilchard, the inner loop will never run: uniqueArray has a starting legth of 0 so it is never cycled ad no values are added to it.
Furthermore, the if condition of the inner loop is also wrong: assuming that the array contains values, every time a non-matching value is found the tested value is appended.
This is a possible solution keeping the code similar to the one you proposed:
Instead of using the inner loop, you can use the array built-in method
includes
to check whether the element is already in the array or not.P.S
A better approach would be to use the set (because includes will work fast in hash set).
Regarding your code you try to add to the unique array while looping it which never happens initially. So you should add to the unique array outside the check loop.
But by my benchmarks using
Set
is the fastest way to get a unique array in JS. Using an array is the slowest –o(n^2)
.Using Array’s built-in methods like
Array::reduce()
andArray::includes()
instead of manual looping gives more decent results.Btw, I find that using a block label is elegant in that case and isn’t the label anti-pattern since the label’s scope is very local.