Вопрос

Having trouble not getting the way to achieve the following with the array. I intend to reduce the array to unique values, although, getting the total count for each of the unique elements. For instance, get a final array like:

var data = [14:"A",5:"IMG",2:"SPAN"]

which corresponds to the total of items in each unique tag, associated with the tag itself. My original sample array is the following:

var data = ["A", "A","A","IMG","IMG","A","A","IMG","A","A","IMG","A","A","IMG","IMG","A","A","A","A","A","SPAN","SPAN"]

Это было полезно?

Решение

You cannot get

var data = [14:"A",5:"IMG",2:"SPAN"]

because that is not valid JavaScript. Also, if the count would end up being similar for different tags, you would get duplicate keys. Turn the key/values around, and use JavaScript object:

var reduced = {A: 14, IMG: 6, SPAN: 2};  

In Ecmascript 5:

var data = ["A","A","A","IMG","IMG","A","A","IMG","A","A","IMG","A","A","IMG","IMG","A","A","A","A","A","SPAN","SPAN"]; 

var reduced = data.reduce(function (result, item) {
    result[item] = (result.hasOwnProperty(item) ? result[item] : 0) + 1; 
    return result; 
}, {}); 

console.log(reduced); // Object {A: 14, IMG: 6, SPAN: 2}

jsFiddle here

If you need to support browsers without "reduce", you can find reduce in underscore.js

var reduced = _.reduce(data, function (result, item) {
    result[item] = (result.hasOwnProperty(item) ? result[item] : 0) + 1; 
    return result; 
}, {}); 

jsFiddle with underscore here

Другие советы

var data = ["A", "A", "A", "IMG", "IMG", "A", "A", "IMG", "A", "A", "IMG", "A", "A", "IMG", "IMG", "A", "A", "A", "A", "A", "SPAN", "SPAN"];
var temp = [];
$.each(data,function(i,v){
 if ($.inArray(v, temp) == -1) temp.push(data[i]);
});
var count = [];
var c = 0;
$.each(temp,function(i,v){
  $.each(data,function (index, val) {
    if (v == val) c++;
   });
   count.push(c);
   c = 0;
});
var obj = {};
for (var i = 0; i < count.length; i++) {
  obj[temp[i]] = count[i]
 }
 console.log(obj); //Object { A=14, IMG=6, SPAN=2}

http://jsfiddle.net/aqPb2/2/

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top