Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filter unique items from jQuery array

Tags:

jquery

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

enter image description here

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.

like image 623
NealR Avatar asked Dec 15 '22 10:12

NealR


1 Answers

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()

like image 96
Lix Avatar answered Feb 08 '23 09:02

Lix