Array.diff ( 6 kyu )

문제

Your goal in this kata is to implement an difference function, which subtracts one list from another.

It should remove all values from list a, which are present in list b.

array_diff([1,2],[1]) == [2]

If a value is present in b, all of its occurrences must be removed from the other:

array_diff([1,2,2,2,3],[2]) == [1,3]

b의 원소를 a에서 지워서 리턴하는 문제

풀이

function array_diff(a, b) {
  for ( let i = 0; i < b.length; i++ ) {
    while ( a.indexOf(b[i]) !== -1 ) {
      a = a.slice(0, a.indexOf(b[i])).concat(a.slice(a.indexOf(b[i])+1, a.length));
    }
  }
  return a;
}

for, while로 a에 b의 원소들이 없을때까지 반복해서 리턴

다른 사람의 풀이

function array_diff(a, b) {
  return a.filter(function(x) { return b.indexOf(x) == -1; });
}

고수..


+ Recent posts