本文介绍了JS新设置,删除重复项不区分大小写?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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-insensitiveso the expected result should be

但它似乎不起作用...

but it doesn't seem to work...

推荐答案

JavaScript比较器是大小写敏感。对于字符串,您可能需要先清理数据:

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];






或者,您可以使用 reduce()使用自定义嵌套比较逻辑。 下面的实现比较忽略大小写的项目,但对于相等的字符串,它选择第一次出现,无论它的大小写是什么:


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 = function(x) { return 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]

这篇关于JS新设置,删除重复项不区分大小写?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-11 07:41