0

I am working with a JSON array and I am trying to remove duplicates from being posted on the HTML page when I run the loop. Currently I see both images with the same category pizza on the page. How can I make it so it shows only one pizza category with an image? I want to hide the others. Hoping someone can show me what I need to do. Below is my code:

(function() {
  'use strict';

  var url = 'path to json';

  $.getJSON(url, function(json) {
    var data = (json);
    var images = '';

      var uniqueNames = [];
   
      //retrieve values from json file
      $.each(data, function(i, item) {
      if($.inArray(item, uniqueNames) === -1) uniqueNames.push(item)
         images += '<div class="col-md-6 col-sm-6">' + '<img class="img img-responsive img-hover imgCategory" src="' + (item[0].imageURL) + '">' + '<h1>' + (item[0].category) + '</h1>' + '</div>';
     
         });
      //append results to div
      $('#images').html(images);
  });
})();
/*JSON Sample */
[
  [{
    "category": "pasta",
    "imageURL": "path to image"
  }],
  [{
    "category": "pizza",
    "imageURL": "path to image"
  }],
  [{
    "category": "pizza",
    "imageURL": "path to image"
  }]
]
Tom
  • 305
  • 1
  • 3
  • 15

1 Answers1

0

Try this approach:

var arr = [], //collect id values 
    collection = []; //collect unique object

$.each(json_all, function (index, value) {
    if ($.inArray(value.id, arr) == -1) { //check if id value not exits
        arr.push(value.id);//push id value in arr
        collection.push(value); //put object in collection to access later
    }
});
Neo
  • 3,309
  • 7
  • 35
  • 44
  • i tried that but it doesnt seem to work – Tom Oct 14 '16 at 15:31
  • currently i am trying this approach var uniqueNames = []; //retrieve values from json file $.each(data, function(i, item) { if($.inArray(item, uniqueNames) === -1) uniqueNames.push(item) images += '
    ' + '' + '

    ' + (item[0].category) + '

    ' + '
    '; }); //append results to div $('#images').html(images);
    – Tom Oct 14 '16 at 15:34
  • will update code at top as well – Tom Oct 14 '16 at 15:34