Check for duplicates in the case-sensitive Javascript array

advertisements

My solution for checking if duplicates existed in an array using UnderscoreJS:

function hasDups(arr) {
   return arr.length !== _.uniq(arr).length;
}

This would work if the duplicate values were identical, but what about if one was in uppercase and the other was in lowercase? This _.uniq function wouldn't remove those kinds of duplicates.


you can provide a function to uniq which will be used to transform elements:

function toLowerCase(s) {
    if (typeof(s) === 'string') {
        return s.toLowerCase();
    }

    return s;
}

function hasDups(arr) {
    return (arr.length !== _.uniq(arr, false, toLowerCase).length);
}

Hope this helps.

Reference: http://underscorejs.org/#uniq