给定一个排序数组,我想创建一个包含匹配元素数组的新二维数组。类似于python的itertools.groupby
的行为示例:
input = ['a','a','a','a','d','e','e','f','h','h','h','i','l','m','n','r','s','s','t','u','v','y','y']
output = [ ['a','a','a','a'], ['d'], ['e','e'], ['f'], ['h','h','h'], ['i'], ['l'], ['m'], ['n'], ['r'], ['s','s'], ['t'], ['u'], ['v'], ['y','y']]
答案 0 :(得分:1)
您可以检查前一个并在推送到最后一个项目之前添加一个新数组。
var input = ['a', 'a', 'a', 'a', 'd', 'e', 'e', 'f', 'h', 'h', 'h', 'i', 'l', 'm', 'n', 'r', 's', 's', 't', 'u', 'v', 'y', 'y'],
output = input.reduce(function (r, a, i, aa) {
if (aa[i - 1] !== a) {
r.push([]);
}
r[r.length - 1].push(a);
return r;
}, []);
console.log(output);
.as-console-wrapper { max-height: 100% !important; top: 0; }
对于非排序项,您可以在哈希表上使用闭包。
var input = ['a', 'a', 'a', 'a', 'y', 'h', 'h', 'i', 'l', 'e', 'e', 'f', 'h', 'm', 'n', 'r', 's', 'y', 'd', 's', 't', 'u', 'v'],
output = input.reduce(function (hash) {
return function (r, a) {
if (!hash[a]) {
hash[a] = [];
r.push(hash[a]);
}
hash[a].push(a);
return r;
};
}(Object.create(null)), []);
console.log(output);
.as-console-wrapper { max-height: 100% !important; top: 0; }
答案 1 :(得分:0)
您可以将Array.prototype.join()
与参数""
,String.prototype.match()
与RegExp
/([a-z]+)(?=\1)\1|[^\1]/g
一起使用,以匹配一个或多个"a"
到{{1} }后跟捕获的字符,或未捕获的组,"z"
,.map()
.split()
答案 2 :(得分:0)
注意:即使数组未排序,这也会有效:
Set objIE = CreateObject("InternetExplorer.Application")
objIE.Top = 0
objIE.Left = 0
objIE.Width = 800
objIE.Height = 600
objIE.Visible = True
objIE.Navigate ("http://www.baseball-reference.com/boxes/BOS/BOS199004090.shtml")
Do
DoEvents
If Err.Number <> 0 Then
objIE.Quit
Set objIE = Nothing
GoTo j:
End If
Loop Until objIE.ReadyState = 4
item = objIE.Document.getElementsByClassName("suppress_csv sortable stats_table now_sortable")(0).getElementsByTagName("td")(0)