Cho mảng ký tự có phần tử trùng. Gom các ký tự giống nhau thành các mảng con riêng biệt (giữ nguyên thứ tự xuất hiện đầu tiên).
Ví dụ
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));
Kết quả
[ [ 'a', 'a', 'a', 'a' ], [ 'd' ], [ 'e', 'e' ], [ 'f' ], [ 'h', 'h', 'h' ], [ 'i' ], [ 'l' ], [ 'm' ], [ 'n' ], [ 'r' ], [ 's', 's' ], [ 't' ], [ 'u' ], [ 'v' ], [ 'y', 'y' ] ]