JS new set, remove duplicates case insensitive?

前端 未结 3 1658
醉梦人生
醉梦人生 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 03:56

    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]
    

提交回复
热议问题