5

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.

2
  • what do you expect, if you have [1, 2, 3, 7, 7, 7, 7]? Commented Sep 23, 2015 at 9:28
  • 1
    @NinaScholz, the expected result should be [1, 2, 3, 7, 7, 7, 7] Commented Sep 23, 2015 at 9:38

6 Answers 6

3

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]
Sign up to request clarification or add additional context in comments.

Comments

2

Here is my method using JQuery and it does not assume the array is already sorted.

It will iterate through the array and no duplicates to tempResultArray, once finished, it will then add them to the existing result and repeat the process again to find duplicates.

This is not the most efficient method, but it can be handled by one function and does not require the array to be sorted.

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

while (myArray && myArray.length) {
    myArray = customSort(myArray);
}
console.log(result);

function customSort(myArray){
    var tempResultArray = [], tempMyArray = [];
    $.each(myArray, function(i, el){
        if($.inArray(el, tempResultArray ) === -1){ 
            tempResultArray.push(el);
        }else{
            tempMyArray.push(el); 
        }
   });  
    tempResultArray.sort(function(a, b){return a-b});
    $.merge( result,tempResultArray)
    return tempMyArray;
}

JSFiddle

Comments

2

This proposal features a straight forward approach with focus on array methods.

function sprout(array) {
    return array.reduce(function (r, a) {
        !r.some(function (b) {
            if (b[b.length - 1] < a) {
                b.push(a);
                return true;
            }
        }) && r.push([a]);
        return r;
    }, []).reduce(function (r, a) {
        return r.concat(a);
    });
}

document.write('<pre>' + JSON.stringify(sprout([1, 1, 2, 2, 2, 3, 4, 4, 4]), 0, 4) + '</pre>');
document.write('<pre>' + JSON.stringify(sprout([1, 2, 3, 7, 7, 7]), 0, 4) + '</pre>');
document.write('<pre>' + JSON.stringify(sprout([1, 1, 2, 3, 3, 4, 5, 5, 6, 6, 6, 6, 6, 7]), 0, 4) + '</pre>');

Comments

2

here's another solution:

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


function mySequelArray(arr) {
    var res = arguments[1] || [];
    var nextVal;
    var min = Math.min.apply(null, arr);

    if (res.length > 0) {
        nextVal = arr.filter(function (x) {
            return x > res[res.length - 1]
        }).sort()[0] || min;
    } else {
        nextVal = min;
    }
    res.push(nextVal);
    arr.splice(arr.indexOf(nextVal), 1);

    return (arr.length > 0) ? mySequelArray(arr, res) : res;


}

console.log(mySequelArray(myArray))

fiddle

Comments

1

My best approach will be to split your array into separate arrays for each repeated value, then arrange each separate array and join altogether.

Comments

1

UPDATED: I wrote a quick code sample that should work if the same number in inputArray is not given more than twice. You could improve it by making it recursive thus creating new arrays for each new number and removing the limitation. Had some free time so i re-wrote a recursive function to sort any given array in sequence groups like you wanted. Works like a charm, inputArray does not need to be sorted and doesn't require any libraries. Jsfiddle here.

var inputArray = [3, 4, 1, 2, 3, 1, 2, 4, 1, 2, 5, 1];
var result = sortInSequence(inputArray);
console.log(result); //output: [1, 2, 3, 4, 5, 1, 2, 3, 4, 1, 2, 1]

function sortInSequence(inputArray){
    var inputArraySize = inputArray.length,
        tempArray = [], //holds new array we are populating
        sameValuesArray = [], //holds same values that we will pass as param in recursive call
        rSorted = []; //init sorted array in case we have no same values

    for(var i = inputArraySize; i > 0; i--){
        var value = inputArray.pop();
        tempArray.push(value);

        var counter = 0,
            tempArraySize = tempArray.length;
        for(var j = 0; j < tempArraySize; j++){
            if(tempArray[j] == value){
                counter++;
            }
        }

        if(counter == 2){
            //value found twice, so remove it from tempArray and add it in sameValuesArray
            var sameValue = tempArray.pop();
            sameValuesArray.push(sameValue);
        }
    }

    if(sameValuesArray.length > 0){
        rSorted = sortInSequence(sameValuesArray);
    }

    tempArray.sort();
    return tempArray.concat(rSorted);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.