About the unique Javascript Array

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'] 

is he wrong I think it should output [12, 'ss', 'sdd', 'kk', '12'], is it possible to fix this promble?

+4
source share
2 answers

Key names are always converted to a string. I recommend using Array.prototype.indexOf to check if an array entry is unique or not. The indexOf method also behaves correctly with respect to 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] correct behavior: it is different if the references to the objects 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 
+3
source

When the number 12 used as a dictionary key, it was translated into a string, making it the same key as the last line of '12'

+1
source

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


All Articles