qazerty23 qazerty23 - 4 months ago 16
Javascript Question

Javascript code infinite loop

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;
}

Answer

There is no need for nested loop. you can check the result for available values with Array.prototype.indexOf or Array.prototype.includes methods.

var strings = ["audi", "audi", "bmw", "bmw", "bmw", "bmw", "audi", "audi", "8-()"];

function unique(arr) {
  var result = [];
  result.push(arr[0]);

  for (var i = 1; i < arr.length; i++) {
    if (result.indexOf(arr[i]) === -1)
      result.push(arr[i]);


  }
  return result;
}
console.log(unique(strings))

BTW chef suggest is:

var strings = ["audi", "audi", "bmw", "bmw", "bmw", "bmw", "audi", "audi", "8-()"];
console.clear();

var result = strings.filter(s => this[s] ? false : (this[s] = true), Object.create(null))

console.log(result);

Comments