简体   繁体   English

检查重复项时如何忽略数组中的空值-Javascript

[英]How to ignore empty values in array when checking for duplicates - Javascript

In Javascript, I am testing two arrays to check for duplicates. 在Javascript中,我正在测试两个数组以检查重复项。 I found a nice simple way to do this in ES6 我在ES6中找到了一种不错的简单方法

 function hasDuplicates(MyArray) { return new Set(MyArray).size !== MyArray.length; } 

However, I want it to ignore empty values in the array, as it counts empty values as a duplicate. 但是,我希望它忽略数组中的空值,因为它会将空值视为重复项。

My array looks like this: ["name 0", "name", "name 2", "", ""] 我的数组如下所示:[“名称0”,“名称”,“名称2”,“”,“”]

How can I do this? 我怎样才能做到这一点?

Just add this line before return statement 只需在return语句之前添加此行

var tmpArray = MyArray.filter( s => (s || !isNaN(s)) && String(s).length > 0 );

And use this array in return statement 并在return语句中使用此数组

return new Set( tmpArray ).size !== tmpArray.length;

Or just extend the same line to check for duplicates 或者只是延长同一行以检查重复项

return MyArray.filter( ( s, i, arr ) => 
         (s || !isNaN(s)) && String(s).length > 0 
           && arr.indexOf( s, i + 1 ) != -1 ).length > 0; 

This will return true if there are duplicates. 如果有重复,则返回true

If you want to return the dupe array as result, this is my solution to your problem: 如果要返回dupe数组作为结果,这是我对您的问题的解决方案:

let data = ["101", "", "", "666"];
let compData = ["", "", "666", "101"];
var result = data.filter((value) => {
    if(value !="" && compData.indexOf(value) > -1)
        return value;
})   

outputs: 输出:

["101", "666"]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM