I've got a jquery json request and in that json data I want to be able to sort by unique values. so I have
我有一个jquery json请求,在json数据中我希望能够按唯一值排序。所以我有
{"people":[{"pbid":"626","birthDate":"1976-02-06","name":'name'},{"pbid":"648","birthDate":"1987-05-22","name":'name'},.....
So, far, i have this
所以,到目前为止,我有这个
function(data){ $.each(data.people, function(i, person){ alert(person.birthDate); }
but, I am at a total loss as to how efficiently get only the unique birthDates, and sort them by year (or any sort by any other personal data).
但是,我完全失去了如何有效地获得唯一的birthDates,并按年份(或任何其他个人数据)进行排序。
I'm trying to do this, and be efficient about it (i'm hoping that is possible).
我正在努力做到这一点,并且有效率(我希望这是可能的)。
Thanks
谢谢
3 个解决方案
#1
9
I'm not sure how performant this will be, but basically I'm using an object as a key/value dictionary. I haven't tested this, but this should be sorted in the loop.
我不确定这将是多么高效,但基本上我使用一个对象作为键/值字典。我没有测试过这个,但是应该在循环中进行排序。
function(data) {
var birthDates = {};
var param = "birthDate"
$.each(data.people, function() {
if (!birthDates[this[param]])
birthDates[this[param]] = [];
birthDates[this[param]].push(this);
});
for(var d in birthDates) {
// add d to array here
// or do something with d
// birthDates[d] is the array of people
}
}
#2
6
function(data){
var arr = new Array();
$.each(data.people, function(i, person){
if (jQuery.inArray(person.birthDate, arr) === -1) {
alert(person.birthDate);
arr.push(person.birthDate);
}
});
}
#3
3
Here's my take:
这是我的看法:
function getUniqueBirthdays(data){
var birthdays = [];
$.each(data.people, function(){
if ($.inArray(this.birthDate,birthdays) === -1) {
birthdays.push(this.birthDate);
}
});
return birthdays.sort();
}
#1
9
I'm not sure how performant this will be, but basically I'm using an object as a key/value dictionary. I haven't tested this, but this should be sorted in the loop.
我不确定这将是多么高效,但基本上我使用一个对象作为键/值字典。我没有测试过这个,但是应该在循环中进行排序。
function(data) {
var birthDates = {};
var param = "birthDate"
$.each(data.people, function() {
if (!birthDates[this[param]])
birthDates[this[param]] = [];
birthDates[this[param]].push(this);
});
for(var d in birthDates) {
// add d to array here
// or do something with d
// birthDates[d] is the array of people
}
}
#2
6
function(data){
var arr = new Array();
$.each(data.people, function(i, person){
if (jQuery.inArray(person.birthDate, arr) === -1) {
alert(person.birthDate);
arr.push(person.birthDate);
}
});
}
#3
3
Here's my take:
这是我的看法:
function getUniqueBirthdays(data){
var birthdays = [];
$.each(data.people, function(){
if ($.inArray(this.birthDate,birthdays) === -1) {
birthdays.push(this.birthDate);
}
});
return birthdays.sort();
}