我有一个这样的数组
[-2,4,5,6,7,8,10,11,15,16,17,18,21]有谁知道如何使该数组的输出成为整数,如下所示
-2,4-8,10-11,15-18,21输出将把连续的数字变为一个数字
这些东西对我来说都是新的,任何帮助都将不胜感激,谢谢!
发布于 2021-02-25 13:23:41
下面我创建了一个函数,用于将数组中的序列替换为包含其范围的字符串。有三个函数。
getConsectiveCount将以array和index作为参数,并将获取其后连续数字的计数。
replaceFirstConsective将接受数组,并将仅替换数组中的第一个序列。
replaceAllConsectives将替换数组中的所有序列。
const arr = [-2,4,5,6,7,8,10,11,15,16,17,18,21];
const getConsectiveCount = (arr, index) => {
let count = 0;
for(let i = index; i < arr.length; i++){
if(arr[i + 1] === arr[index] + (i - index) + 1){
count++;
}
}
return count;
}
console.log(getConsectiveCount(arr, 1));
const replaceFirstConsective = (arr) => {
for(let i = 0; i < arr.length; i++){
let count = getConsectiveCount(arr,i);
if(count){
return [...arr.slice(0, i), `${arr[i]}-${arr[i + count]}`, ...arr.slice(i + count + 1)]
}
}
return arr;
}
const replaceAllConsectives = (arr) => {
for(let i = 0; i < arr.length;i++){
arr = replaceFirstConsective(arr)
}
return arr;
}
console.log(JSON.stringify(replaceAllConsectives(arr)))
发布于 2021-02-25 13:30:28
const inp = [-2,4,5,6,7,8,10,11,15,16,17,18,21];
let res = [];
for(let i=0;i
Check this if it helps.
发布于 2021-02-25 13:32:09
我已经做到了:
const arr1 = [-2,4,5,6,7,8,10,11,15,16,17,18,21]
const arr2 = arr1.reduce((a,c,i,{[i+1]:nxt})=>
{
if (!a.s1) a.s1 = c.toString(10)
if ( (c+1) !== nxt )
{
a.s1 += a.s2 ? `_${a.s2}` : ''
a.r.push(a.s1)
a.s1 = a.s2 = ''
}
else a.s2 = nxt.toString(10)
return (nxt===undefined) ? a.r : a
},{r:[],s1:'',s2:''})
console.log(JSON.stringify( arr2 )).as-console-wrapper { max-height: 100% !important; top: 0; }
https://stackoverflow.com/questions/66362600
复制相似问题