Advertisement
Coldsewoo

Untitled

Oct 23rd, 2019
354
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. const array = ["a", "a", "b", "b", "c", "c", "c", "c", "d", "d", "e"]
  2.  
  3. function arrayCompress(arr) {
  4.   if(!arr.length) return []
  5.   const result = []
  6.   let current = arr.shift()
  7.   let count = 1
  8.   result.push(current)
  9.   while(arr.length) {
  10.     let next = arr.shift()
  11.     if(current === next) count += 1
  12.     else {
  13.       if(count !== 1) {
  14.         result.push(count)
  15.         result.push(next)
  16.       }
  17.       else {
  18.         result.push(next)
  19.       }
  20.  
  21.       count = 1
  22.     }
  23.     current = next
  24.   }
  25.   if(count !== 1) result.push(count)
  26.  
  27.   return result
  28. }
  29. arrayCompress(array)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement