const x = [-6, -3, -2, -1, 0, 1, 3, 4, 5, 7, 8, 9, 10, 11, 14, 15, 17, 18, 19, 20]; const solve = x => { const sorted = x.sort((a, b) => a - b); const grouped = sorted.map((x, i, a) => i == a.findIndex((x2, i2) => i2 - x2 == i - x) && a.filter((x2, i2) => i2 - x2 == i - x) || []); const ranged = grouped.map(x => x.length > 2 ? x[0] + '-' + x.slice(-1)[0] : x); return ranged.flat().join(','); } console.log(solve(x));
Of course solve can be re-written as one-liner if you feel the need for that.
Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment's permalink.
Hide child comments as well
Confirm
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
Of course solve can be re-written as one-liner if you feel the need for that.