JSFiddle - React, Tailwind, and code Playground

by krustnic

JavaScript

const data = [3, 2, 1, 5, 6, -1, 9, 10] // "-1,1-3,5-6,10"
// -1 1 2 3 4 6 10

function squeeze(arr) {
	const sorted = arr.sort((a, b) => {
  	return a - b
  })
  
  let start = sorted[0]
  let stop  = sorted[0]
  const out = []
  
  /*
  let i=0
  do {
  	if (sorted[i+1] - sorted[i] === 1) {
    	stop += 1
    } else {
    	if (start !== stop) {
      	out.push(start + '-' + stop)
      } else {
      	out.push(sorted[i])
      }    	
      
    	start = sorted[i+1]
      stop = sorted[i+1]
    }
    
  	i += 1
  } while(i<sorted.length)
  */
  
  /*
  for(let i=0; i<sorted.length - 1; i++) {
  	if (sorted[i+1] - sorted[i] === 1) {
    	stop += 1
    } else {
    	if (start !== stop) {
      	out.push(start + '-' + stop)
      } else {
      	out.push(sorted[i])
      }    	
      
    	start = sorted[i+1]
      stop = sorted[i+1]
    }
  }
  
  if (start !== stop) {
    out.push(start + '-' + stop)
  } else {
    out.push(sorted[sorted.length - 1])
  } 
  */
  
  return out
}

console.log(squeeze(data))