JavaScript: create a uniqid() function

PHP provides a uniqid() function that generates a random identifier. This function makes use of a timestamp and a random number to generate the ID. We can create something similar with JavaScript, though not so accurate. Let's see the details.

First we need an helper function to remove duplicates from an array:

var unique = function(origArr) {
    var newArr = [],
        origLen = origArr.length,
        found, x, y;

    for (x = 0; x < origLen; x++) {
        found = undefined;
        for (y = 0; y < newArr.length; y++) {
            if (origArr[x] === newArr[y]) {
                found = true;
                break;
            }
        }
        if (!found) {
            newArr.push(origArr[x]);
        }
    }
    return newArr;
};

Then we'll use a JavaScript timestamp (generated via the Date object) to create our identifier:

var uniqID = function() {
    var ts = +new Date;
    var tsStr = ts.toString();

    var arr = tsStr.split('');
    var rev = arr.reverse();


    var filtered = unique(rev);

    return filtered.join('');

};

We get a date reference expressed in milliseconds. Then we turn this string into an array, we reverse it, we remove all duplicate numbers from it and finally we return the resulting string.

An example:

var test = document.getElementById('test'),
    run = document.getElementById('run');

run.onclick = function() {
    var p = document.createElement('p');
    p.appendChild(document.createTextNode(uniqID()));
    test.appendChild(p);
};​

You can see the demo below.

Demo

Live demo

Back to top