2013-08-29 93 views
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"]

+0

您可以對原始數組(或其深層副本)進行排序,然後對雙打進行計數。順便說一句。在你的例子中有14個「A」和6個「IMG」... – Teemu

+0

http://mattgemmell.com/2008/12/08/what-have-you-tried/ – pckill

+0

謝謝。但問題的確在於,使用與標籤相關的計數來構建新的關聯數組。 – McRui

回答

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

如果您需要支持的瀏覽器沒有 「降低」,你可以找到減少underscore.js

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

jsFiddle with underscore here

+0

非常感謝您的努力和幫助。我更喜歡Ecmascript 5選項,因爲它返回一個對象,這使得它的使用更靈活。對於不支持減少...的瀏覽器WC - 誰在乎;):)再次感謝! – McRui

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/

+0

感謝您的幫助。我更喜歡下面的方法,它似乎更輕量級。謝謝! – McRui

+1

:)歡迎您 – rps