0

无法通过数组实现以下目标。我打算将数组减少为唯一值,但要获取每个唯一元素的总数。例如,得到一个最终数组,如:

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

它对应于每个唯一标签中的项目总数,与标签本身相关联。我的原始示例数组如下:

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

4

2 回答 2

2
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/

于 2013-08-29T09:57:03.483 回答
2

你不能得到

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

因为那不是有效的 JavaScript。此外,如果不同标签的计数最终相似,您将获得重复的键。转动键/值,并使用 JavaScript 对象:

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

在 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在这里

如果需要支持不带reduce的浏览器,可以在underscore.js中找到reduce

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

jsFiddle 带下划线

于 2013-08-29T10:05:44.740 回答