我有一个类似的数组
var arr = [12, 13, 14, 17, 18, 19, 20]
我想知道如何遍历数组,以便根据序列将此数组拆分为 2 个数组?即基本上如果 i+1 != true
使它成为一个新数组
var arr = [12, 13, 14]
var arr2 = [17,18,19,20]
我正在使用 lodash 并尝试了一些使用 splice
的 for
语句,但我有点困惑?感谢任何帮助
最佳答案
var a = [1, 2, 3, 5, 6, 7];
var r = [];
var t = [];
for (var i = 0; i < a.length; ++i)
{
if (i == 0)
{
t.push(a[i]); // add the first element and continue
continue;
}
if (a[i - 1] != (a[i] - 1))
{
// if the current is not sequential
// add the current temporary array to arrays result
r.push(t);
// clear the temporary array and start over
t = [];
}
t.push(a[i]);
}
r.push(t);
r
将包含您所有的数组
function seq(e,t,n,r){t=[];n=[];for(r=0;r<e.length;++r){if(!r){n.push(e[r]);continue}if(e[r-1]!=e[r]-1){t.push(n);n=[]}n.push(e[r])}t.push(n);return t}
var result = seq([1, 2, 3, 5, 6, 7]);
关于javascript - 根据序列javascript拆分数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16886176/