Advertisement
CR7CR7

cleanTheRoom

May 8th, 2023
840
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function cleanTheRoom(arr) {
  2.   // sort the array in ascending order
  3.   arr.sort((a, b) => a - b);
  4.   // initialize an empty array to store the result
  5.   let result = [];
  6.   // initialize a variable to store the current element
  7.   let current = null;
  8.   // initialize a variable to store the count of the current element
  9.   let count = 0;
  10.   // loop through the array
  11.   for (let num of arr) {
  12.     // if the current element is null or different from the num
  13.     if (current === null || current !== num) {
  14.       // if the count is more than one, push an array of the current element and count to the result
  15.       if (count > 1) {
  16.         result.push(Array(count).fill(current));
  17.       }
  18.       // else if the count is one, push the current element to the result
  19.       else if (count === 1) {
  20.         result.push(current);
  21.       }
  22.       // update the current element and count
  23.       current = num;
  24.       count = 1;
  25.     }
  26.     // else if the current element is equal to the num, increment the count
  27.     else {
  28.       count++;
  29.     }
  30.   }
  31.   // handle the last element and count
  32.   if (count > 1) {
  33.     result.push(Array(count).fill(current));
  34.   } else if (count === 1) {
  35.     result.push(current);
  36.   }
  37.   // return the result
  38.   return result;
  39. }
  40.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement