Filter unique elements from jQuery array

I am trying to get all unique Field names from the returned results of an Ajax call. However, for some reason, the name Field DRMrole continues to appear twice.

Here is the jQuery I'm 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 is the data 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 every time I run this code, so it doesn't seem random.

+4
source share
3 answers

You can always use an object instead of an array - placing each element as a property of the object. Each identical key that you tried to insert would simply replace 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 pointed out in a comment from sbeliv01 ) is to use $.inArray() to check if an element exists:

 var fieldArray = []; $.each(data, function(i, item){ if ($.inArray(item.Field,fieldArray) === -1){ fieldArray.push(item.Field); } }); 

Link - $.inArray()

+14
source

Alternatively, if you already have an array that you want to "uniqueinize"

 Array.prototype.getUnique = function(){ var u = {}, a = []; for(var i = 0, l = this.length; i < l; ++i){ if(u.hasOwnProperty(this[i])) { continue; } a.push(this[i]); u[this[i]] = 1; } return a; } 
+1
source

var x = [2, 3, 6, 3, 2, 5];

x = x.filter (function (a, b, c) {return c.indexOf (a, - c.length)> = b? true: false;});

-3
source

Source: https://habr.com/ru/post/1480174/


All Articles