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

时间:2017-10-27 10:23:22

标签: javascript jquery

我有这样的数组:

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']);
                        });
                    })
                });

1 个答案:

答案 0 :(得分:2)

您可以尝试使用此代码

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)

相关问题