[1,1, 2,2,3,4] 到 [[1,1],[2,2],3,4 ]
function action(list) {
let result = [];
list.forEach(l => {
let i = result.findIndex(r => {
if (r instanceof Array)
return r[0] === l;
return r === l;
});
if (i === -1)
result.push(l); // 不存在就加入
else if (result[i] instanceof Array)
result[i].push(l); // 存在数组就加入数组
else // 存在单个就改为数组
result[i] = [result[i], l];
});
return result;
}
题主的要求不多,也不知道是否还有其他限制。
这些都不太清楚。
var data = [1, 1, 1, 2, 2, 3, 4]
function result(data) {
let lastResult = null;
let colIndex = 0;
let array = []
for (let i = 0; i < data.length; i++) {
if (lastResult != data[i]) {
colIndex++;
array[colIndex - 1] = data[i]
} else {
if (array[colIndex - 1] instanceof Array) {
array[colIndex - 1].push(data[i])
} else {
array[colIndex - 1] = [array[colIndex - 1], data[i]]
}
}
lastResult = data[i];
}
return array
}
result(data) // [[1,1,1],[2,2],3,4]
13 回答13k 阅读
7 回答2.1k 阅读
3 回答1.3k 阅读✓ 已解决
6 回答1.2k 阅读✓ 已解决
2 回答1.4k 阅读✓ 已解决
3 回答1.3k 阅读✓ 已解决
6 回答1.1k 阅读
抛砖引玉
评论中的数据格式写法: