0

I have array like this:

var arr = [
{"id":1,"tipe":"foo"},
{"id":2,"tipe":"bar"},
{"id":3,"tipe":"bar"}
];

how to get unique data on javascript or jquery, and show result like this:

[{"id":1,"tipe":"foo"},{"id":2,"tipe":"bar"}];

this is my code for get the data:

$('#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']);
                        });
                    })
                });
silvia zulinka
  • 728
  • 3
  • 18
  • 39
  • 1
    unique based on what criteria? – user2736738 Oct 27 '17 at 10:24
  • Maybe this [stackoverflow link](https://stackoverflow.com/questions/13207527/how-to-find-whether-object-exist-in-array-or-not-javascript) can help you – Shubham Baranwal Oct 27 '17 at 10:26
  • Refer below links: https://stackoverflow.com/questions/2218999/remove-duplicates-from-an-array-of-objects-in-javascript https://stackoverflow.com/questions/15125920/how-to-get-distinct-values-from-an-array-of-objects-in-javascript – Mr. Raj Kale Oct 27 '17 at 10:32

1 Answers1

2

You can try using this code

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

Demo

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)
Carsten Løvbo Andersen
  • 26,637
  • 10
  • 47
  • 77