Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery distinct array

I have array textbox something like below

<input type="text" name="txtname[]" value="single" />
<input type="text" name="txtname[]" value="twin" />
<input type="text" name="txtname[]" value="single" />
<input type="text" name="txtname[]" value="dulex" />
<input type="text" name="txtname[]" value="single" />

I wanna show those value to...

single -------- 3
twin -------- 1
dulex -------- 1

like image 734
foekall Avatar asked Dec 11 '25 15:12

foekall


1 Answers

var txtname = $(':input[name="txtname[]"]').map(function(a,b){ return $(b).val(); }).toArray();

var unique = {};
$.each(txtname, function(a,b){
    if (!unique[b])
        unique[b] = 0;
    unique[b]++;
});

unique ended up with:

({single:3, twin:1, dulex:1})

UPDATE

In case you want it as a jQuery add-on:

$.fn.extend({
    unique_count: function(){
        var unique = {};
        this.each(function(a,b){
            var v = $(b).val();
            if (!unique[v])
                unique[v] = 0;
            unique[v]++;
        });
        return unique;
    },
    unique_vals: function(){
        var unique = [];
        $.each($(this).unique_count(), function(a,b){ unique.push(a); });
        return unique;
    }
});

And the output being:

var $inputs = $(':input[name="txtname[]"]');
$inputs.unique_count() // = Object: {single:3, twin:1, dulex:1}
$inputs.unique_vals()  // = Array:  ["single", "twin", "duplex"]
like image 93
Brad Christie Avatar answered Dec 16 '25 01:12

Brad Christie



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!