In a xml document, I would like to retrieve with jQuery the distinct attributes values for “name” attribute of the elements “product”, deleting the duplicates.
However, I haven’t had any success with unique() function or creating an array, as suggested in this discussion here:
How to use jQuery to select XML nodes with unique text content?
Any help will be sincerly appreciated.
Thank you so much in advance.
My XML:
<products>
<product name="first"></product>
<product name="second"></product>
<product name="first"></product>
<product name="first"></product>
</products>
My not working code:
function getName() {
$.ajax({
type: "GET",
url: xmlFile.xml,
dataType: "xml",
success: function(xml) {
$(xml).find('product').each(function(){
var name = $(this).attr('name');
var productArray = new Array();
if( jQuery.inArray(name, productArray) == -1 ){
$('<p></p>').html(name).appendTo('body');
productArray.push(name);
}
});
}
});
}
productArray is gettin defined for each iteration of the product element and hence the inArray is always returning -1.
Move the definition of productArray outside the each loop i.e.: