JS new set, remove duplicates case insensitive?

前端 未结 3 1657
醉梦人生
醉梦人生 2021-01-06 03:17
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 re

3条回答
  •  难免孤独
    2021-01-06 04:18

    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]
    

提交回复
热议问题