et arr = [1,2,3,4,5,6,6,7,8,9,10,10,10,11,12,12,4,5]如何通过js 把它切成 [1,2,3,4,5,6] [6,6] [6,7,8,9,10] [10,10,10] [10,11,12] [12,12] [12,4,5]规则: 1、相邻不同的合为一组; 2、相邻相同的合为一组。
2 回答
手掌心
TA贡献1942条经验 获得超3个赞
let arr = [1,2,3,4,5,6,6,7,8,9,10,10,10,11,12,12,4,5] let splitArray = function (A) { let global = [[A[0]]], local = global[0] for (var i = 1; i < A.length; i++) { let p = local[local.length - 1], pp = local[local.length - 2] if (A[i] === p && (p === pp || !pp) || A[i] !== p && p !== pp) { local.push(A[i]) } else { local = [A[i - 1], A[i]] global.push(local) } } return global } console.log(splitArray(arr))
拉风的咖菲猫
TA贡献1995条经验 获得超2个赞
let arr = [1, 2, 3, 4, 5, 6, 6, 7, 8, 9, 10, 10, 10, 11, 12, 12, 4, 5]//结果二维数组let result = [[]]//结果二维数组最后的索引let resultLastIndex = 0//当前 不同 0 / 相同 1 标示let currentFlag = 0arr.forEach((item, index) => { let r = result[resultLastIndex] let compare = r[r.length - 1] if (item !== compare) { if (currentFlag === 0) { r.push(item) } else { currentFlag = 0 result.push([arr[index - 1], item]) resultLastIndex++ } } else { if (currentFlag === 0) { currentFlag = 1 result.push([arr[index - 1], item]) resultLastIndex++ } else { r.push(item) } } })console.log(result)
添加回答
举报
0/150
提交
取消