jquery - Count duplicates within observableArray and Display them -


i have observable array following data

["volkswagen",  "toyota",  "volkswagen",  "toyota",  "audi",  "volkswagen",  "toyota",  "audi"] 

i know how can count duplicate values , display them within select box. like:

volkswagen (3) audi (2) toyota (3) 

what best way achieve this?

i'd use straightforward computed:

viewmodel.collapsedmakes = ko.computed({   pure: true,   owner: viewmodel,   read: function() {     var makes = {}, rv;     // use object count them     this.makes().foreach(function(make) {       if (makes[make]) {         ++makes[make];       } else {         makes[make] = 1;       }     });      // build array     rv = object.keys(makes).sort().map(function(make) {       return make + " (" + makes[make] + ")";     });     return rv;   } }); 

live example:

var viewmodel = {    makes: ko.observablearray([      "volkswagen",      "toyota",      "volkswagen",      "toyota",      "audi",      "volkswagen",      "toyota",      "audi"    ])  };    viewmodel.collapsedmakes = ko.computed({    pure: true,    owner: viewmodel,    read: function() {      var makes = {}, rv;      // use object count them      this.makes().foreach(function(make) {        if (makes[make]) {          ++makes[make];        } else {          makes[make] = 1;        }      });        // build array      rv = object.keys(makes).sort().map(function(make) {        return make + " (" + makes[make] + ")";      });      return rv;    }  });    ko.applybindings(viewmodel, document.body);
<select data-bind="options: collapsedmakes"></select>  <script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>


Comments

Popular posts from this blog

asp.net mvc - SSO between MVCForum and Umbraco7 -

Python Tkinter keyboard using bind -

ubuntu - Selenium Node Not Connecting to Hub, Not Opening Port -