Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort an array sequencial in javascript?

I'm not sure if the title of this question is correct or not and also not sure what the appropriate keyword to search on google.

I have an array look like:

var myArray = [1,1,2,2,2,3,4,4,4];

and I want to sort my array into:

var myArray = [1,2,3,4,1,2,4,2,4];

Please in to my expected result. the order is ascending but duplicate value will repeated on last sequence instead of put it together in adjacent keys. So the expected result grouped as 1,2,3,4 1,2,4 and 2,4.

Thank you for your help and sorry for my bad English.

like image 480
Habibillah Avatar asked Sep 23 '15 07:09

Habibillah


1 Answers

This code works. But it may exist a better solution.

// We assume myArray is already sorted
var myArray = [1,1,2,2,2,3,4,4,4],
    result = [];

while (myArray.length) {
   var value = myArray.shift();

   // Find place
   var index = 0;
   while(result[index] && result[index][result[index].length - 1] == value) index++;

   if(!result[index]) {
      result[index] = [];
   }  

   result[index][result[index].length] = value;
}

result.reduce(function(current, sum) {
  return current.concat(sum);
});

console.log(result) // Display [1, 2, 3, 4, 1, 2, 4, 2, 4]
like image 166
Magus Avatar answered Sep 29 '22 07:09

Magus