About the Javascript Array unique

var arr1 = [12,'ss','sdd','sdd','kk'];
function unique(array){
  var o = {},b = [];
  for(var i=0;i<array.length;i++){
       o[array[i]] = true;
  return b;
unique(arr1) //It works fine .output [12,'ss','sdd','kk']

but,it has some issues on arr2 below:

var arr2 =  [12,'ss','sdd','sdd','kk','12'];//output [12,'ss','sdd','kk']

does it make wrong?I think it should output [12,'ss','sdd','kk','12'],can we fixed this promble?


Key names are always converted to a string. I recommend to use Array.prototype.indexOf in order to check whether an array entry is unique or not. The indexOf method also behaves correctly regarding objects[1].

Demo: http://jsfiddle.net/YE9jx/

function unique(array){
  var b = [];
  for(var i=0; i<array.length; i++){
     if(b.indexOf(array[i]) == -1) b.push(array[i]);
  return b;

[1] The correct behaviour is: Different if the object references are different:

var obj1 = [1,2];
var obj2 = [1,2];
unique([obj1, obj2]);  //[[1,2], [1,2]]  // Because they're different arrays
unique([obj1, obj1]);  //[[1,2]]         // Because both elements are obj1

When the number 12 was used as a dictionary key, it was promoted to string, making it the same key as the last string '12'

Need Your Help

ApplicationPoolIdentity permissions and UserPrincipal

asp.net iis-7 application-pool directoryservices

I've been receiving a COM Exception when performing an AD Search in an ASP.NET 4.0: An operations error occurred (0x80072020)

Waiting for Robospice requests to finish

android json spring robospice

I'm using Robospice in my Android app to get data in JSON format from the server. When the user logs in for the first time, I would like to perform few requests to get data needed for the first run...

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.