这是一个简单的数据集
data = [
{'artist':'a','song':'a'},
{'artist':'a','song':'b'},
{'artist':'a','song':'c'},
{'artist':'b','song':'d'},
{'artist':'b','song':'e'},
{'artist':'c','song':'f'},
{'artist':'d','song':'g'},
{'artist':'d','song':'h'},
{'artist':'d','song':'i'}
];
javascript或jQuery中是否有任何本机函数可以让我以简洁的表达式获得分裂艺术家的数量?
答案 0 :(得分:4)
要获得不同艺术家的数量,您可以使用此功能:
Object.keys(data.reduce(function(p, c) { p[c.artist] = 1 ; return p }, {})).length
这是一个在对象c.artist
中累积p
的不同值的单行,然后计算有多少个键。
答案 1 :(得分:0)
您可以尝试这样:
var array = [{"artist":"a","song":"a"}, {"artist":"a","song":"b"}, {"artist":"a","song":"c"}]
var unique = {};
var distinct = [];
for( var i in array ){
if( typeof(unique[array[i].song]) == "undefined"){
distinct.push(array[i].song);
}
unique[array[i].song] = 0;
}
var d = document.getElementById("d");
d.innerHTML = "" + distinct;
答案 2 :(得分:0)
尝试此操作, DEMO 此处
data = [
{'artist':'a','song':'a'},
{'artist':'a','song':'b'},
{'artist':'a','song':'c'},
{'artist':'b','song':'d'},
{'artist':'b','song':'e'},
{'artist':'c','song':'f'},
{'artist':'d','song':'g'},
{'artist':'d','song':'h'},
{'artist':'d','song':'i'}
];
newdata=[];
$.each(data, function(index,value){
newdata[index]=data[index].artist;
});
alert($.unique(newdata));