[Javascript] array deduplication

Source: Internet
Author: User
Tags map class
Array deduplication

Src: http://yiminghe.javaeye.com/blog/524716

This is a classic problem. After removing the repeated elements in the array, I searched the internet and found that most of them are the solution regardless of reposted or original:


Solution:

Js Code
  1. Function uniq (array ){
  2. Var map = {};
  3. Var re = [];
  4. For (var I = 0, l = array. length; I <l; I ++ ){
  5. If (typeof map [array [I] = "undefined "){
  6. Map [array [I] = 1;
  7. Re. push (array [I]);
  8. }
  9. }
  10. Return re;
  11. }
function uniq(array) {var map={};var re=[];for(var i=0,l=array.length;i<l;i++) {if(typeof map[array[i]] == "undefined"){map[array[i]]=1;re.push(array[i]);}}return re;}

If you have used advanced languages such as java, there is no problem with this code: the following example:

Js Code
  1. Uniq ([1, 2, 2, 4]);
uniq([1,2,1,2,4]);

It can also run normally.



Try the following example again:

Js Code
  1. Uniq ([{x: 1}, "[object Object]"]);
  2. Uniq ([{x: 1 },{ z: 2}]);
uniq([{x:1},"[object Object]"]);uniq([{x:1},{z:2}]);

 

You will know where the error is!

HashMap In Java:

In java, the HashMap class can use objects as keys (internal implementation uses hashcode to hash to the bucket and equals in the bucket [Default memory address] comparison), such:

Java code
  1. Class Holder {
  2. Int I;
  3. }
  4. Public class Test3 {
  5. /**
  6. * @ Param args
  7. */
  8. Public static void main (String [] args ){
  9. HashMap <Holder, Holder> map = new HashMap <Holder, Holder> ();
  10. Holder key = new Holder ();
  11. Holder value = new Holder ();
  12. Value. I = 1;
  13. Map. put (key, value );
  14. Holder key2 = new Holder ();
  15. System. out. println (map. get (key). I );
  16. System. out. println (map. get (key2 ));
  17. }
  18. }
class Holder {int i;}public class Test3 {/** * @param args */public static void main(String[] args) {HashMap<Holder, Holder> map=new HashMap<Holder, Holder>();Holder key= new Holder();Holder value= new Holder();value.i=1;map.put(key, value);Holder key2=new Holder(); System.out.println(map.get(key).i);System.out.println(map.get(key2));}}

Object In Javascript:

In javascript, after all, there is no map. Only objects are defined. Objects Require that their attribute values be strings. If the attribute provided to objects is not strings, the toString method will be automatically called to convert it to the string format, for example:

Js Code
  1. Var x = {};
  2. Var y = {
  3. ToString: function (){
  4. Return "z ";
  5. }
  6. };
  7. X [y] = 1;
  8. Alert (x ["z"]);
var x={};var y={    toString:function(){        return "z";     }};x[y]=1;alert(x["z"]);

The above example shows why the first program is wrong.

Correct answer:

We cannot use the map class library provided by the advanced language, so we have to traverse the array twice. It is also the standard answer provided by taobao ued:


Note === use.

Js Code
  1. /**
  2. * Unique the array
  3. * @ Param {Array} array to unique
  4. * @ Return {Array} uniqued array, note change parameter
  5. */
  6. Function undulpicate (array ){
  7. For (var I = 0; I <array. length; I ++ ){
  8. For (var j = I + 1; j <array. length; j ++ ){
  9. // Note ====
  10. If (array [I] === array [j]) {
  11. Array. splice (j, 1 );
  12. J --;
  13. }
  14. }
  15. }
  16. Return array;
  17. }
/*** Unique the array * @ param {Array} array Array to unique * @ return {array} uniqued array, note change parameter */function undulpicate (array) {for (var I = 0; I <array. length; I ++) {for (var j = I + 1; j <array. length; j ++) {// note === if (array [I] === array [j]) {array. splice (j, 1); j -- ;}} return array ;}

 

Ps: Jquery Uniq Node


If we confirm that each element in the array is an object, we can add tags to the object elements to increase the time complexity to O (n ):

Js Code
  1. Var x = {z: 1 };
  2. Var y = {q: 2 };
  3. Function uniqObjects (array ){
  4. Var re = [];
  5. For (var I = 0, l = array. length; I <l; I ++ ){
  6. If (typeof array [I] ["_ uniqObjects"] = "undefined "){
  7. // Add tags
  8. Array [I] ["_ uniqObjects"] = 1;
  9. Re. push (array [I]);
  10. }
  11. }
  12. // Retrieve the tag
  13. For (var I = 0, l = re. length; I <l; I ++ ){
  14. Delete re [I] ["_ uniqObjects"];
  15. }
  16. Return re;
  17. }
  18. UniqObjects ([x, y, x]);
Var x = {z: 1}; var y = {q: 2}; function uniqObjects (array) {var re = []; for (var I = 0, l = array. length; I <l; I ++) {if (typeof array [I] ["_ uniqObjects"] = "undefined ") {// Add the tag array [I] ["_ uniqObjects"] = 1; re. push (array [I]) ;}/// retrieves the tag for (var I = 0, l = re. length; I <l; I ++) {delete re [I] ["_ uniqObjects"];} return re;} uniqObjects ([x, y, x]);

This is exactly the idea of jquery. Since each element is a node array, you can do this:

Js Code
  1. Unique: function (array ){
  2. Var ret = [], done = {};
  3. Try {
  4. For (var I = 0, length = array. length; I <length; I ++ ){
  5. Var id = jQuery. data (array [I]);
  6. If (! Done [id]) {
  7. Done [id] = true;
  8. Ret. push (array [I]);
  9. }
  10. }
  11. } Catch (e ){
  12. Ret = array;
  13. }
  14. Return ret;
  15. },
unique: function( array ) {var ret = [], done = {};try {for ( var i = 0, length = array.length; i < length; i++ ) {var id = jQuery.data( array[ i ] );if ( !done[ id ] ) {done[ id ] = true;ret.push( array[ i ] );}}} catch( e ) {ret = array;}return ret;},

 

 

Note: Do not use this method for basic types, such as number and string. They will generate temporary objects and cannot achieve the expected results!

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.