function range (arr) {
arr.sort((a, b) => a - b)
let str = arr[0]
let iteration
for (let i = 1; i < arr.length; i++) {
if (arr[i] + 1 === arr[i + 1]) {
iteration = true
} else {
if (!iteration) {
str += ',' + arr[i]
} else {
str += '-' + arr[i]
if (arr[i + 1] + 1 === arr[i + 2]) {
str += ',' + arr[i + 1]
}
iteration = false
}
}
}
return str
}
const range = arr => arr
.sort((a, b) => a - b)
.reduce((agg, v) => {
const currRange = agg[agg.length - 1]
if (!currRange || v > currRange.last + 1) {
agg.push({first: v, last: v})
} else {
currRange.last = v
}
return agg
}, [])
.map(v => v.first + (v.first !== v.last ? '-' + v.last : '')).join()
[ 1, 2 ]
, например. Или [ 5, 6, 8, 9 ]
.const range = ([...arr]) => arr
.sort((a, b) => a - b)
.reduce((acc, n, i, a) => (
(n === a[i - 1] + 1) || acc.push([ n ]),
acc[acc.length - 1][1] = n,
acc
), [])
.map(([ a, b ]) => a === b ? a : `${a}-${b}`)
.join(', ');
const range = arr => ''.concat(...arr
.slice()
.sort((a, b) => a - b)
.reduce((acc, n, i, a) => (
n !== a[i - 1] + 1 && acc.push(i ? `, ${n}` : n),
n === a[i - 1] + 1 && n !== a[i + 1] - 1 && acc.push(`-${n}`),
acc
), [])
);
function range(array: number[]): string {
return array.sort(
(a, b) => a - b
).reduce((acc, next, i) => {
const prev = array[i - 1];
if (prev !== undefined && next - prev === 1) {
acc[acc.length - 1][1] = next;
}
else {
acc.push([next]);
}
return acc;
}, []).map(
arr => arr.join("-")
).join(", ");
}
console.log(range([1, 4, 5, 2, 3, 9, 8, 11, 0])); // 0-5, 8-9, 11
console.log(range([1, 4, 3, 2])); // 1-4
console.log(range([1, 4])); // 1, 4
console.log(range([1])); // 1
console.log(range([])); // ""
const zip = arr => arr
.reduce((agg, c) => {
const iR = agg.indexOf(c + 1);
const iL = agg.lastIndexOf(c - 1);
if (!!~iR && !!~iL) agg.splice(iL, 2); // закрыли дырку
else if (!!~iR) agg[iR] = c; // сдвинули границу
else if (!!~iL) agg[iL] = c; // то же
else { // вставляем сироту - найти позицию сразу после меньшего
let pos = 0;
while (pos < agg.length && agg[pos] < c) pos++;
agg.splice(pos, 0, c, c); // вставляем дважды
}
return agg;
}, [])
.reduce((agg, c, i, arr) => {
if (!(i&1)) agg.push(arr[i+1] === c ? c : [c, arr[i+1]].join('-'));
return agg;
}, [])
.join(', ')
;
[ 0, 5, 8, 9, 11, 11 ]
indexOf()
и lastIndexOf()
на самописный поиск, останавливающийся на элементе, бОльшем или меньшем искомого.reduce()
передаётся текущий индекс и сам массив, это позволяет упростить backreference. В итоге у меня получилось нечто подобное:/**
* @param {Array} list
* @return {string}
*/
const range = list => list
.sort((a,b) => a - b)
.reduce((r, v, i, a) => {
if (i > 0 && v - a[i - 1] === 1) {
let l = r.pop();
l.push(v);
r.push(l);
} else {
r.push([v]);
}
return r;
}, [])
.map(v => v.length > 1 ? `${v.shift()}-${v.pop()}` : v)
.join(', ');
.sort((a,b) => a - b)
- не знал function range (a) {
if (a.length < 2) return a
a.sort( (a, b) => a-b )
let pred = null
let e = false
let result = ''
for (let i of a) {
if (pred === null) {
result = pred = i
continue
}
if (i != pred+1 ) {
e ? result += '-' + pred + ', ' + i : result += ', ' + i
e = false
} else e = true
pred = i
}
if (e) result += '-' + pred
return result
}
console.log(range([1, 4, 5, 2, 3, 9, 8, 11, 0]))
console.log(range([1, 4, 3, 2]))
console.log(range([1, 4, 8]))
function range (a) {
a.sort( (a, b) => a-b )
a = [...a,'']
return a.reduce((st, item, i, arr) => i==0 ? st += item : ( item != arr[i-1]+1 ) ? st += '-' + arr[i-1] + ', ' + item : st = st, '')
.split(',')
.map((item) => (eval(item) == 0 ? item.slice(0, item.indexOf('-')) : item).trim())
.slice(0, -1)
.join(', ')
}
console.log(range([1, 4, 5, 2, 3, 9, 8, 11, 0]))
console.log(range([1, 4, 3, 2]))
console.log(range([1, 4, 8]))
const range = a => [...a.sort( (a, b) => a-b ),''].reduce((st, item, i, arr) => i==0 ? st += item : ( item != arr[i-1]+1 ) ? st += '-' + arr[i-1] + ', ' + item : st = st, '')
.split(',')
.map((item) => (eval(item) == 0 ? item.slice(0, item.indexOf('-')) : item).trim())
.slice(0, -1)
.join(', ')
console.log(range([1, 4, 5, 2, 3, 9, 8, 11, 0]))
console.log(range([1, 4, 3, 2]))
console.log(range([1, 4, 8]))
const rangeIt = data => {
const a = [...data].sort((a, b) => a-b), r = [[a[0], a[0]]];
for (i = 1; i < a.length; i++) {
if (r[r.length - 1][1] + 1 === a[i]) {
r[r.length - 1][1] = a[i];
} else {
r.push([a[i], a[i]]);
}
}
return r.map(rr => rr[0] === rr[1] ? rr[0] : rr.join('-')).join(', ');
}
const rangeIt = data => {
const a = [...data].sort((a, b) => a - b), r = [[a[0], a[0]]];
const calcRanges = (n, i) => {
if (!i) return;
if (r[r.length - 1][1] + 1 === n) {
r[r.length - 1][1] = n;
} else {
r.push([n, n]);
}
};
a.forEach(calcRanges);
return r.map(rr => rr[0] === rr[1] ? rr[0] : rr.join('-')).join(', ');
}