다음과 같이 반복되는 알파벳을 포함하는 알파벳 배열이 있다고 가정해 보겠습니다. -
const arr = [ 'a','a','a','a','d','e','e','f','h','h','h','i','l','m','n', 'r','s','s',' t','u','v','y','y' ];
그러한 배열을 취하는 JavaScript 함수를 작성해야 합니다. 함수는 모든 동일한 알파벳을 고유한 하위 배열로 그룹화해야 합니다.
따라서 위의 배열의 경우 출력은 다음과 같아야 합니다. -
const output = [ ['a','a','a','a'], ['d'], ['e','e'], ['f'], ['h','h','h'], ['i'], ['l'], ['m'], ['n'], ['r'], ['s','s'], ['t'], ['u'], ['v'], ['y','y'] ];
예시
이에 대한 코드는 -
const arr = [
'a','a','a','a','d','e','e','f','h','h','h','i','l','m','n','r','s','s','
t','u','v','y','y'
];
const bringAlong = (arr = []) => {
const hash = {};
return arr.reduce(function(res, e) {
if(hash[e] === undefined)
hash[e] = res.push([e]) − 1;
else
res[hash[e]].push(e);
return res;
}, []);
};
console.log(bringAlong(arr)); 출력
콘솔의 출력은 -
[ [ 'a', 'a', 'a', 'a' ], [ 'd' ], [ 'e', 'e' ], [ 'f' ], [ 'h', 'h', 'h' ], [ 'i' ], [ 'l' ], [ 'm' ], [ 'n' ], [ 'r' ], [ 's', 's' ], [ 't' ], [ 'u' ], [ 'v' ], [ 'y', 'y' ] ]