gpt4 book ai didi

javascript - 如何在 javascript 或 jquery 中获取数组的唯一数据?

转载 作者:行者123 更新时间:2023-12-01 02:51:01 24 4
gpt4 key购买 nike

我有这样的数组:

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)

关于javascript - 如何在 javascript 或 jquery 中获取数组的唯一数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46972857/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com