带计数的唯一关联数组

时间:2013-08-29 09:30:57

标签: javascript jquery arrays unique associative

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

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"]

2 个答案:

答案 0 :(得分: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/

答案 1 :(得分: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 here

如果您需要支持没有“reduce”的浏览器,可以在underscore.js

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

js表示下划线here