This question has already been answered:

Is it possible to do without the str variable declared in the outer loop and directly compare arr[i] with result[i] ?

I have only one consideration about this, which would store the beginning of the outer loop in the variable str , in case of expansion or making changes to the function. Because, otherwise, after a full pass of the outer loop, the beginning will not be saved anywhere. But maybe I am I wrong? Let arr be an array of strings.

Write the function unique(arr) , which returns an array containing only unique arr elements. For example, something would be output an array of strings: krishna, hare, 8- ().

 function unique(arr) { var result = []; nextInput: for (var i = 0; i < arr.length; i++) { var str = arr[i]; // для каждого элемента for (var j = 0; j < result.length; j++) { // ищем, был ли он уже? if (result[j] == str) continue nextInput; // если да, то следующий } result.push(str); } return result; } var strings = ["кришна", "кришна", "харе", "харе", "харе", "харе", "кришна", "кришна", "8-()" ]; console.log(unique(strings)); // кришна, харе, 8-() 

Reported as a duplicate at Grundy. javascript 10 May '18 at 15:00 .

A similar question was asked earlier and an answer has already been received. If the answers provided are not exhaustive, please ask a new question .

  • Perhaps it was an attempt to optimize on the knee? Well, the operation of extracting an element from an array is probably not instantaneous ... - test123
  • According to the code, all this is here, for good, to be rewritten in Set / HashSet. And the speed will increase much more. (And yes, the nextInput label is exactly at that place? It would be reasonable for me, following the logic of the code, if it went after the first for (;;), though ... this is js ...) - test123
  • one
    Yes you can. Cho to think that. - Lexx918
  • Does js have a continue on label? How can I forget this? - vp_arth
  • Strange why, duplicate? The link went .. yes there is the same task .. but the solution through the object .. I decided so .. but the nuances of exactly the slow solution of this example are interesting - ZdraviSmisl

1 answer 1

You can do a little easier with filter :

 function unique(arr) { return arr.filter((curr, index, self) => self.indexOf(curr) === index); } const strings = ["кришна", "кришна", "харе", "харе", "харе", "харе", "кришна", "кришна", "8-()" ]; console.log(unique(strings)); 

And if they pester with computational complexity, you can hide everything:

 function unique(arr) { return Array.from(new Set(arr)); } const strings = ["кришна", "кришна", "харе", "харе", "харе", "харе", "кришна", "кришна", "8-()" ]; console.log(unique(strings)); 

Read more: Set , Array.from ()

  • So-so decision - About (n ^ 2) - vp_arth