var g_Year = [
{ Year: "2011" },
{ Year: "2011" },
{ Year: "2010" },
{ Year: "2012" },
{ Year: "2011" },
{ Year: "2012" }
];
fxnDrop = function () {
$.each(g_Year , function (index, Ele) {
var iYear = g_Year [index].Year,
sHtmlYear = '<option value="' + iYear + '">' + iYear + '</option>';
$("#DropDown_Year").each(function (index, Ele) {
$("#DropDown_Year").append(sHtmlYear);
if (Ele.value != iYear) {
$("#DropDown_Year").remove(sHtmlYear);
}
});
});
}
这里我有多年,我的目标是在下拉框中只显示特定年份一次。例如:2011年必须在下拉框中只显示一次。任何人都可以帮助我做到这一点。我在Dropbox中获得了多个2011年值。
答案 0 :(得分:2)
试试此代码
var fxnDrop = function() {
var yearsArray = [];
$.each(g_Year, function(index) {
if($.inArray(+g_Year[index].Year , yearsArray) == -1){
yearsArray.push(+g_Year[index].Year);
}
});
yearsArray.sort();
var sHtmlYear = '';
$.each(yearsArray , function(i){
sHtmlYear += '<option value="'+ yearsArray[i] +'">'
+ yearsArray[i] + '</option>';
});
$("#DropDown_Year").append(sHtmlYear);
};
fxnDrop();
<强> Check Fiddle 强>
答案 1 :(得分:0)
你可以使用Jquery.inArray()
函数:对于exe: -
var categories=[];
if ($.inArray(value.category, categories)==-1){
categories.push(value.category);
}
categories
将保留您需要的唯一类别
的更新强>
[SEE LIVE DEMO][2]
答案 2 :(得分:0)
尝试这个..使用@pranav
提到的Jquery.inArray()var yeararray= [];
fxnDrop = function () {
$.each(g_Year , function (index, Ele) {
if ($.inArray(Ele.Year, yeararray)==-1) {
var iYear = g_Year [index].Year,
sHtmlYear = '<option value="' + iYear + '">' + iYear + '</option>';
$("#DropDown_Year").each(function (index, Ele) {
$("#DropDown_Year").append(sHtmlYear);
if (Ele.value != iYear) {
$("#DropDown_Year").remove(sHtmlYear);
}
});
yeararray.push(Ele.Year);
}
});
}
答案 3 :(得分:0)
var g_Year = [
{ Year: "2011" },
{ Year: "2011" },
{ Year: "2010" },
{ Year: "2012" },
{ Year: "2011" },
{ Year: "2012" }
];
g_Year.sort(function(o1, o2){return o1.Year > o2.Year} );
// use reduce function
var uniqueG_Year = g_Year.reduce(function(previousValue, currentValue, index, array){
if(previousValue.length == 0 || previousValue[previousValue.length-1].Year != currentValue.Year)
previousValue.push(currentValue);
return previousValue;
}, []);
// or simply use filter
var uniqueG_YearFiltered = g_Year.filter(function(element, index, array){
return (index == 0 || array[index-1].Year != element.Year)
});