Gists
This is a sample script for compiling the continuous numbers using Google Apps Script. For example, the values of [4, 5, 9, 3, 10, 5, 11, 7, 7, 13, 1] are converted to ["1","3-5","7","9-11","13"].
Sample script
const compilingNumbers = (ar) => {
const { values } = [...new Set(ar.sort((a, b) => a - b))].reduce(
(o, e, i, a) => {
if (
o.temp.length == 0 ||
(o.temp.length > 0 && e == o.temp[o.temp.length - 1] + 1)
) {
o.temp.push(e);
} else {
if (o.temp.length > 0) {
o.values.push({ start: o.temp[0], end: o.temp[o.temp.length - 1] });
}
o.temp = [e];
}
if (i == a.length - 1) {
o.values.push(
o.temp.length > 1
? { start: o.temp[0], end: o.temp[o.temp.length - 1] }
: { start: e, end: e }
);
}
return o;
},
{ temp: [], values: [] }
);
return values;
};
// Please run this function.
function main() {
const ar = [4, 5, 9, 3, 10, 5, 11, 7, 7, 13, 1]; // This is sample values.
const values = compilingNumbers(ar);
console.log(values);
const res = values.map(({ start, end }) =>
start == end ? start.toString() : `${start}-${end}`
);
console.log(res);
}
When this script is run, console.log(values) and console.log(res) show [{"start":1,"end":1},{"start":3,"end":5},{"start":7,"end":7},{"start":9,"end":11},{"start":13,"end":13}] and ["1","3-5","7","9-11","13"], respectively. From this result, it is found that the continuous numbers were compiled.