Simple count of unique items in javascript array -


looking count of unique filenames contained in simple javascript array.

i have javascript array combines 2 arrays via

var total_dl = prev_dl.concat(new_dl).sort(); 

one json_encode() php variable, other made checkbox values selected on form. outputs simple list of file names, ie

    cat.jpg, dog.jpg, elephant.jpg, cat.jpg, lion.jpg, dog.jpg  

i can refine array of distinct values,

var unique_dl = total_dl.filter((value,pos) => {return total_dl.indexof(value) == pos;} );   

to output

    cat.jpg, dog.jpg, elephant.jpg, lion.jpg 

i need output count of how many unique/distinct filenames contained here, ie 4. first thought use length

var count_unique = unique_dl.length;  

which seems give value of prev_dl + 1, unchanged whatever new_dl made of. try with

var count_unique = unique_dl.filter(function(val, i, arr) {      return arr.indexof(val) === i; }).length; 

fails (have misformatted here?).

any pointers/steers here welcome, thanks.

the unique_dl.length solution works me. building unique_dl thou needs o(n^2) time, it's slower than:

function count_unique(in_array) {     if(in_array.length == 0)         return 0;     var sorted = input_array.sort();     var unique_count = 1;     for(int = 1; < sorted.length; ++i)         if(sorted[i - 1] != sorted[i])             ++unique_count;     return unique_count;  } 

since uses o(n log(n)) time


Comments

Popular posts from this blog

Is there a better way to structure post methods in Class Based Views -

performance - Why is XCHG reg, reg a 3 micro-op instruction on modern Intel architectures? -

jquery - Responsive Navbar with Sub Navbar -