Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JS new set, remove duplicates case insensitive?

var arr = ['verdana', 'Verdana', 2, 4, 2, 8, 7, 3, 6];
result =  Array.from(new Set(arr));

console.log(arr);
console.log(result);

i want to remove any duplicates case-insensitive so the expected result should be

['Verdana', 2, 4, 8, 7, 3, 6]

but it doesn't seem to work...

like image 313
Francesco Avatar asked Oct 14 '17 04:10

Francesco


3 Answers

JavaScript comparator is case sensitive. For strings you may need to clean up the data first:

var arr = ['verdana', 'Verdana', 2, 4, 2, 8, 7, 3, 6]
  .map(x => typeof x === 'string' ? x.toLowerCase() : x);
result =  Array.from(new Set(arr));
// produces ["verdana", 2, 4, 8, 7, 3, 6];

Alternatively, you may use reduce() with a custom nested comparing logic. The implementation below compares the items ignoring the case, but for "equal" strings it picks the first occurrence, regardless what its "casing" is:

'verdana', 'Moma', 'MOMA', 'Verdana', 2, 4, 2, 8, 7, 3, 6]
  .reduce((result, element) => {
    var normalize = x => typeof x === 'string' ? x.toLowerCase() : x;

    var normalizedElement = normalize(element);
    if (result.every(otherElement => normalize(otherElement) !== normalizedElement))
      result.push(element);

    return result;
  }, []);
// Produces ["verdana", "Moma", 2, 4, 8, 7, 3, 6]
like image 184
Igor Soloydenko Avatar answered Oct 14 '22 01:10

Igor Soloydenko


var arr = ['verdana', 'Verdana', 2, 4, 2, 8, 7, 3, 6];

function getUniqueValuesWithCase(arr, caseSensitive){
    let temp = [];
    return [...new Set(caseSensitive ? arr : arr.filter(x => {
        let _x = typeof x === 'string' ? x.toLowerCase() : x;
        if(temp.indexOf(_x) === -1){
            temp.push(_x)
            return x;
        }
    }))];
}
getUniqueValuesWithCase(arr, false); // ["verdana", 2, 4, 8, 7, 3, 6]
getUniqueValuesWithCase(arr, true);  // ["verdana", "Verdana", 2, 4, 8, 7, 3, 6]
like image 3
allan valooran Avatar answered Oct 14 '22 02:10

allan valooran


You can use Set after converting the string elements to uppercase.Here ... is spread operator

var arr = ['verdana', 'Verdana', 2, 4, 2, 8, 7, 3, 6];

var result = arr.map(function(item) {
  return typeof item === "string" ? item.toString().toUpperCase() : item
})

result = [...new Set(result)];

console.log(result);
like image 1
brk Avatar answered Oct 14 '22 00:10

brk