user8481001
user8481001

Reputation: 1

Simple count of unique items in javascript array

looking for a count of unique filenames are contained in a simple javascript array.

I have a javascript array that combines two arrays via

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

One is a json_encode() from a php variable, the other is made from the checkbox values selected on a form. This outputs a simple list of file names, ie

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

I can then refine this into an array of distinct values, with

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 now just need to output a count of how many unique/distinct filenames are contained here, ie 4. First thought was to use length

var count_unique = unique_dl.length; 

which seems to give a value of prev_dl + 1, unchanged for whatever new_dl is made up of. Another try with

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

fails too (have I misformatted here?).

Any pointers/steers here would be very welcome, thanks.

Upvotes: 0

Views: 189

Answers (3)

dork
dork

Reputation: 4568

You can use the Set object. It takes an iterable and returns a set with unique items.

const arr = 'cat.jpg, dog.jpg, elephant.jpg, cat.jpg, lion.jpg, dog.jpg'.split(', ');
const unique = new Set(arr);

console.log(unique.size);

And if you want to convert it back to an array, you can use Array.from:

const uniqueArr = Array.from(unique);

console.log(uniqueArr);

const arr = 'cat.jpg, dog.jpg, elephant.jpg, cat.jpg, lion.jpg, dog.jpg'.split(', ');
const unique = new Set(arr);

console.log('Set size', unique.size);

const uniqueArr = Array.from(unique);

console.log('Unique array', uniqueArr);

Upvotes: 1

coffidev
coffidev

Reputation: 999

I have test your example and as @phil said, with the data you provide the result is 4.

var total_dl = [
  'cat.jpg', 'dog.jpg', 'elephant.jpg', 'cat.jpg',
  'lion.jpg', 'dog.jpg'
]
var unique_dl = total_dl.filter((value,pos) => {return total_dl.indexOf(value) == pos;} );  

console.log(unique_dl)
var count_unique = unique_dl.length; 
console.log(count_unique)

https://jsbin.com/rolaxuh/1/edit?html,js,console

Upvotes: 0

DarioDF
DarioDF

Reputation: 301

The unique_dl.length solution works for me. Building unique_dl thou needs O(n^2) time, so 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 i = 1; i < sorted.length; ++i)
        if(sorted[i - 1] != sorted[i])
            ++unique_count;
    return unique_count;
 }

Since it uses just O(n log(n)) time

Upvotes: 0

Related Questions