4
var arr1 = [12,'ss','sdd','sdd','kk'];
function unique(array){
  var o = {},b = [];
  for(var i=0;i<array.length;i++){
     if(!o[array[i]]){
       b.push(array[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?

1
  • The comma after var i=0 should be a semicolon. Commented Dec 17, 2011 at 10:12

2 Answers 2

3

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
Sign up to request clarification or add additional context in comments.

1 Comment

+1. But note that not all browsers support Array.indexOf() - if you want to allow for this you can add the code shown here at MDN.
1

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'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.