在JavaScript中对数组中的匹配元素进行分组
假设我们有一个字母数组,其中包含一些重复的字母,例如:
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' ] ]