I am trying to pull all unique Field
names from the returned results of an Ajax call. However, for whatever reason, the Field
name DRMrole
continues to appear twice.
Here is the jQuery I am using
//Construct array to determine unique Field names
var fieldArray = [];
$.each(data, function(i, item){
fieldArray.push(item.Field);
console.log(item.Field);
});
fieldArray = $.unique(fieldArray);
console.log(fieldArray);
And here are the readouts from the console.log
commands
As you can see, for some reason DRMrole
appears twice in the filtered results. This happens each and every time I run this code so doesn't appear to be random.
You could always use an object instead of an array - placing each item as a property in the object. Each identical key that you attempted to insert would simple override the existing one:
var fieldArray = {}; // object instead of array
$.each(data, function(i, item){
fieldArray[item.Field] = item.Field;
});
Here is a super simple example on jsFiddle
Another option (as mentioned in a comment by sbeliv01) would be to use the $.inArray()
function to test if an element already exists:
var fieldArray = [];
$.each(data, function(i, item){
if ($.inArray(item.Field,fieldArray) === -1){
fieldArray.push(item.Field);
}
});
Reference - $.inArray()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With