1
model w/ sample data => 
[{
    date: '13413413',
    name: 'asdfasdf',
    other: 'kjh'
}]

getJSON returns 4 arrays of 10 model objects each.

array1 = 10 of resultsObj sorted by date from newest to oldest
array2 = 10 of resultsObj sorted by date from newest to oldest
array3 = 10 of resultsObj sorted by date from newest to oldest
array4 = 10 of resultsObj sorted by date from newest to oldest

I need 1 array with all 40 objects sorted by date, newest to latest.

I think can do this with a lot of if/else checks, but would love to see some examples/ideas, thanks.

1

3 Answers 3

5

This will be easy to understand for you. first concatenate the array into one and chain the output to Array.sort

code

var result = a.concat(b,c,d).sort(function(a, b) {
    return b.date-a.date
});
Sign up to request clarification or add additional context in comments.

1 Comment

wonderful! Thanks so much. Clean and works! good idea to concat all together, I wasn't thinking about that at all.
1

You can do it in one statement without intermediate variables:

var sorted = [].concat.call(array1,array2,array3,array4).sort(function(a,b){
    return b.date-a.date
})

You should have a second look at your design, though, and check you shouldn't have an array of arrays or another structure instead of four variables.

Comments

1

Since the 4 arrays are already sorted, the fastest way is having an index for each one, and find the minimum of the current four:

var indices = [0, 0, 0, 0],
    arrays = [array1, array2, array3, array4],
    array = Array(40);
for(var i=0; i<40; ++j) {
  var min = Infinity, argmin;
  for(var j=0; j<4; ++i) if(indices[j] < 10 && arrays[j][indices[j]] < min) {
    min = arrays[j][indices[j]].date;
    argmin = j;
  }
  array[i] = arrays[argmin][indices[argmin]++];
}

So, if the arrays have n elements, this algorithm is O(4n) = O(n).

A simpler approach would be concatenating all the arrays and sorting, but that would be O(4n log(4n)) = O(n log n).

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.