मान लीजिए, हमारे पास अल्फाबेट्स की एक सरणी है जिसमें कुछ दोहराए गए अल्फाबेट्स हैं जैसे -
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' ] ]