본문 바로가기

algorithm/codewars

[7kyu] Homogenous array

문제설명

Description:

Challenge:

Given a two-dimensional array, return a new array which carries over only those arrays from the original, which were not empty and whose items are all of the same type (i.e. homogenous). For simplicity, the arrays inside the array will only contain characters and integers.

Example:

Given [[1, 5, 4], ['a', 3, 5], ['b'], [], ['1', 2, 3]], your function should return [[1, 5, 4], ['b']].

Addendum:

Please keep in mind that for this kata, we assume that empty arrays are not homogenous.

The resultant arrays should be in the order they were originally in and should not have its values changed.

No implicit type casting is allowed. A subarray [1, '2'] would be considered illegal and should be filtered out.





나의풀이

function filterHomogenous(arrays) { function isHomogenous(element){ var i = 1; var isSame = true; var type = typeof element[0]; if(element.length === 1){ return isSame; }else if(element.length === 0){ return false; }else{ while(isSame && i<element.length){ isSame = (type === typeof element[i]); i++; } return isSame; } } var new_arrays = arrays.filter(isHomogenous);//콜백함수가 true를 리턴하면 new array에 포함 return new_arrays; }




다른사람의 풀이

let filterHomogenous = a => a.filter(b => b.length > 0 && b.every(e => typeof e == typeof b[0]));




느낀점

ES6의 강력함을 느꼈다. 이제 ES6도 공부 했으니 다음부턴 화살표함수도 잘 활용해봐야겠다.

'algorithm > codewars' 카테고리의 다른 글

[6kyu] Tribonacci sequence  (0) 2018.02.08
[6kyu] Simple string expansion  (0) 2018.02.07
[6kyu] crashing boxes  (0) 2018.01.28
[6kyu] playing with digits  (0) 2018.01.28
[6kyu] multiples of 3 or 5  (0) 2018.01.28