简体   繁体   中英

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

In Javascript, I am testing two arrays to check for duplicates. I found a nice simple way to do this in 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", "", ""]

How can I do this?

Just add this line before return statement

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

And use this array in return statement

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.

If you want to return the dupe array as result, this is my solution to your problem:

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

outputs:

["101", "666"]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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