Skip to content

Instantly share code, notes, and snippets.

@k2nr k2nr/gist:3092157
Created Jul 11, 2012

Embed
What would you like to do?
remove duplicates in javascript
function removeDups(array) {
var obj = {},
len = array.length,
res = [],
i;
for(i=0; i < len; i++) {
obj[JSON.stringify(array[i])] = array[i];
}
for(i in obj) {
res.push(obj[i]);
}
return res;
}
@syoichi

This comment has been minimized.

Copy link

syoichi commented Jul 12, 2012

配列のunique化ですね。
ES5.1において、JSON.stringifyNaNInfinity-Infinity'null'にします。

NOTE 4 Finite numbers are stringified as if by calling ToString(number). NaN and Infinity regardless of sign are represented as the String null.

ECMAScript Language Specification - ECMA-262 Edition 5.1

nullNaNInfinity-Infinity+0-0ObjectRegExpFunctionを厳密に区別すると以下の様な実装になりますね。

/*jslint maxlen: 80*/
// Edition 2012-07-10

function arrayUnique(arr) {
    'use strict';

    var results, objList, primHash, i, arrLen, val, type, objListLen,
        contain, key;

    results = [];
    objList = [];
    primHash = {};

    for (i = 0, arrLen = arr.length; i < arrLen; i += 1) {
        val = arr[i];
        type = typeof val;

        if (val && (type === 'object' || type === 'function')) {
            objListLen = objList.length;
            contain = false;

            while (objListLen) {
                contain = val === objList[objListLen -= 1];

                if (contain) {
                    break;
                }
            }

            if (!contain) {
                objList.push(val);
                results.push(val);
            }
        } else {
            key = (val === 0 && 1 / val === -Infinity)
                ? type + '-' + val
                : type + val;

            if (!primHash[key]) {
                primHash[key] = true;
                results.push(val);
            }
        }
    }

    return results;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.