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"
  }]
]
1

1 Answer 1

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
    }
});
Sign up to request clarification or add additional context in comments.

3 Comments

i tried that but it doesnt seem to work
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 += '<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);
will update code at top as well

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.