I'm making a function, which takes an array of values and returns an array with only unique values. For example:
var strings = ["audi", "audi", "bmw", "bmw","bmw","bmw","audi","audi", "8-()"];
Result should be:
alert( unique(strings) ); // audi, bmw, 8-()
I don't understand why my function goes into infinite loop, could anyone help please? Here is the function:
function unique(arr) {
var result = [];
result.push(arr[0]);
for (var i = 1; i < arr.length; i++) {
for (var j = 0; j < result.length; j++) {
if (result[j] != arr[i]) {
result.push(arr[i]);
}
}
}
return result;
}
result.push(arr[i])makesresult.lengthincrease by 1.resultarray will never stop to growconsole.log()statements in the loop(s)?arr[i]item is not equal to the first value inresultthen you add it toresulteven though it may be equal to one of the later values inresult. And if it's not equal to any of the existingresultvalues you'll add it multiple times...