
두 배열이 얼마나 유사한지 확인해보려고 합니다. 문자열 배열 s1과 s2가 주어질 때 같은 원소의 개수를 return하도록 solution 함수를 완성해주세요.
제한사항
function solution(s1, s2) {
let answer = 0;
s2.forEach((el) => {
for(v of s1) {
if (el === v) answer++;
}
})
return answer;
}
function solution(s1, s2) {
const intersection = s1.filter((x) => s2.includes(x));
return intersection.length;
}
와 훨씬 간단하게... 그냥 filter() 메서드를 써서 s2.includes()인 것들만 남기고 배열의 길이를 반환한다.
function solution(s1, s2) {
const concat = [...s1, ...s2];
const setConcat = Array.from(new Set(concat));
return concat.length - setConcat.length;
}