简体   繁体   中英

Javascript: String comparison for inside character issue

Small problem here. I have this challenge below.

Christmas is coming, and Santa has a long list to go through, to find who deserves presents for the big day. Go through a list of children, and return a list containing every child who appeared on Santa's list. Do not add any child more than once. Output should be sorted.

Comparison should be case sensitive, and the returned list return only one copy of each name. "Sam" and "sam" is allowed, but "sAm" and "sAm" is not.

Here's my code

function findChildren(santasList, children) {
    children.forEach(child => {
        santasList.forEach(s => {
            if(child.toLowerCase() === s.toLowerCase()){

                var longerLength = Math.max(child.length, s.length);
                for(var i = 0; i < longerLength; i++){
                    if (child[i] !== s[i]){
                        console.log(child);
                        return i;

                    }
                    console.log(child);
                    break;
                }
            }
        });

    });

}

let santasList = ["Tom", "Errol", "Sam", "mistyMay","Peter","Jennifer", 
"macMerphy"];
let children = ["Errol", "Peter", "jennifer", "mistymay", "MacMerphy"];

findChildren(santasList, children);

This prints; Errol Peter jennifer mistymay MacMerphy

But I believe it should print; Errol Peter jennifer MacMerphy?

Where's the fix?

It is because of

if (child.toLowerCase() === s.toLowerCase()) {

comparison was happening in a case-insensitive manner .

Also, you can improve your code ( currently with O(N^3) ) further by using filter and includes

function findChildren(santasList, children) {
  return children.sort().filter( s => santasList.includes( s ) );
}

Demo

 function findChildren(santasList, children) { return children.sort().filter( s => santasList.includes( s ) ); } let santasList = ["Tom", "Errol", "Sam", "mistyMay", "Peter", "Jennifer", "macMerphy" ]; let children = ["Errol", "Peter", "jennifer", "mistymay", "MacMerphy"]; console.log(findChildren(santasList, children)); 

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