티스토리 뷰

Algorithms

find intersection algorithm

seoca 2021. 3. 28. 23:41

 

중복된 값 string return.

function FindIntersection(strArr){
    let first = strArr[0].split(','); // turn them into array
    let second = strArr[1].split(',');

    //중복되는 value 찾기.
    let filtered = first.filter(function (value){
        return second.includes(value) //case-sensitive. return true if it contains the value.
    })

    //중복없으면 return false.
    if(filtered.length === 0){
        return false;
    }else{
        //array to string using join
        //use replace for regular expression to remove white space.
        return filtered.join(',').replace(/\s/g, ""); // \s: whitespace. /g: globally
    }
}
console.log(FindIntersection(["1,2,5,6,7", "2,5,7,8,15"])); //2,5,7

 

 

 

2. Finding the Intersection of Two Arrays

function FindIntersection(numbersOne, numbersTwo) {
    const answer = [];
    for(let i of numbersTwo){
        if(numbersOne.includes(i)){
            answer.push(i);
        }
    }
    return answer;
}
console.log(FindIntersection([3,4,5,1,3], [1,3,2,4])) // [1,3,4]

'Algorithms' 카테고리의 다른 글

Using array.reduce method to count duplicate elements  (0) 2022.10.23
two sum  (0) 2021.03.26
on sale products algorithm  (0) 2021.02.12
How many typos in a string  (0) 2021.02.12
CamelCase  (0) 2021.02.12