需求是取输入数据中的连续数字,将连续数字使用连接符~连接首尾数字
输入:1,2,3, 5, 6, 9, 12, 13, 14
输出: 1 ~ 3, 5 ~ 6, 9, 12 ~ 14
window.onload = function () {
let input = [1,2,3, 5, 6, 9, 12, 13, 14]
let output = continuousNum(input);
console.log('output', output);
}
const continuousNum = (arr) => {
let res = [];
let str ='';
let i = 0;
res[i] = [arr[i]];
arr.reduce((pre, cur) => {
if (cur - pre === 1) {
res[i].push(cur);
} else {
i++;
res[i] = [cur];
}
return cur;
})
res.forEach(itm => {
let len = itm.length;
if ( len > 1) {
str +=`${itm[0]}~${itm[len-1]},`;
} else {
str += `${itm[0]},`;
}
})
return str.substring(0, str.length-1);
}
网友评论