我有这样的数组:
var arr = [
{"id":1,"tipe":"foo"},
{"id":2,"tipe":"bar"},
{"id":3,"tipe":"bar"}
];
如何在 javascript 或 jquery 上获取唯一数据,并显示如下结果:
[{"id":1,"tipe":"foo"},{"id":2,"tipe":"bar"}];
这是我获取数据的代码:
$('#tipe').change(function(){
var val = $(this).val();
url = '{{url('getdata')}}';
$.ajax({
url:url,
data: {tipe:val}
}).done(function(data){
$('#page').empty();
$.each(data, function(key, value){
$('#page').append(value['halaman']);
});
})
});
您可以尝试使用此代码
var result = arr.reduce(function(t, el1) {
var matches = t.filter(function(el2) {
return el1.tipe == el2.tipe
})
if (matches.length == 0)
t.push(el1)
return t;
}, [])
演示
var arr = [{
"id": 1,
"tipe": "foo"
},
{
"id": 2,
"tipe": "bar"
},
{
"id": 3,
"tipe": "bar"
}
];
var result = arr.reduce(function(t, el1) {
var matches = t.filter(function(el2) {
return el1.tipe == el2.tipe
})
if (matches.length == 0)
t.push(el1)
return t;
}, [])
console.log(result)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句