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

1 Answer 1

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)

Sign up to request clarification or add additional context in comments.

2 Comments

Might be worth throwing a couple of comments in there to explain but otherwise good answer
@MasterYoda True, ill throw some comments in a sec

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.