0

I have these object :

var obj1 = {
  endDateInMs : 125000001
};

var obj2 = {
  endDateInMs: 125000000
};

var obj3 = {
  endDateInMs: 125000002
};

and an array containing these objects :

var array1 = [obj1, obj2, obj3];

I would like to sort array1 by date of object. I would like to have the more recent first and the oldiest at the end of the array.

I do the following but it does'nt work :

function compare(a,b) {
                    if (a.endDateInMs < b.endDateInMs) {
                        return -1;
                    }
                    else if (a.endDateInMs > b.endDateInMs) {
                        return 1;
                    }
                }

var arrayOfHistoryForThisItem = wall_card_array[item];

                    var newArraySorted = arrayOfHistoryForThisItem.sort(compare);
                    var lastElement = newArraySorted[0];
2
  • 1
    What do you mean by it doesn't work? Also, you are missing return 0 in compare(a,b). Commented Mar 31, 2015 at 12:12
  • What do you mean by it doesn't work? Also, you are missing return 0 in compare(a,b). Commented Mar 31, 2015 at 12:12

2 Answers 2

1

Wouldn't it be just

array1.sort(function(a, b) {
    return b.endDateInMs - a.endDateInMs;
});

FIDDLE

Sign up to request clarification or add additional context in comments.

Comments

0

Using the open source project http://www.jinqJs.com, its easy.

See http://jsfiddle.net/tford/epdy9z2e/

    //Use jsJinq.com open source library
var obj1 = {
  endDateInMs : 125000001
};

var obj2 = {
  endDateInMs: 125000000
};

var obj3 = {
  endDateInMs: 125000002
};

var array1Ascending = jinqJs().from(obj1, obj2, obj3).orderBy('endDateInMs').select();
var array1Descending = jinqJs().from(obj1, obj2, obj3).orderBy([{field:'endDateInMs', sort:'desc'}]).select();

document.body.innerHTML = '<pre>' + JSON.stringify(array1Ascending, null, 4) + '</pre>';

document.body.innerHTML += '<pre>' + JSON.stringify(array1Descending, null, 4) + '</pre>';

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.