-4

I need to sort an array like the one below based on the difference between "over" "under" odds of a match, so the most balanced outcome goes to the first row of the main array!

var object = [
        [{"0.5": { "over": 1.2, "under": 3.8 }}], //difference 2.6
        [{"1.5": { "over": 1.5, "under": 2.8 }}], //difference 1.3
        [{"2.5": { "over": 1.9, "under": 2.0 }}], //difference 0.1
        [{"2.5": { "over": 2.2, "under": 1.8 }}], //difference 0.4
    ];

Like this

var object = [
    [{ "2.5": { "over": 1.9, "under": 2.0 } }], //difference 0.1
    [{ "2.5": { "over": 2.2, "under": 1.8 } }], //difference 0.4
    [{ "1.5": { "over": 1.5, "under": 2.8 } }], //difference 1.3
    [{ "0.5": { "over": 1.2, "under": 3.8 } }], //difference 2.6
];

I have read this post but it's not of any help in my case

Sort Complex Array of Arrays by value within

I just solved it. Thanks guys!

var obj = [{ value: 0.5, over: 1.2, under: 3.8 },
        { value: 1.5, over: 1.5, under: 3.2 },
        { value: 2.5, over: 1.8, under: 2.5 },
        { value: 3.5, over: 1.9, under: 1.9 },
        { value: 3.5, over: 2.5, under: 1.75 }];



obj.sort(function(a,b) { 
    return Math.min(Math.abs(parseFloat(b.over) - parseFloat(a.under)));
    });
9
  • How is it not of any help? It shows you how you can sort an array by passing a custom compare callback function. All you need to do is sort your main array, and compare two items in it in your callback. Commented May 17, 2014 at 23:32
  • You have too many arrays there, you don't need the nested arrays. If you just use a colleciton you can try Underscore's sortBy Commented May 17, 2014 at 23:33
  • function(a,b) {return Math.abs(a.over-a.under) - Math.abs(b.over-a.under);} Commented May 17, 2014 at 23:36
  • @NiettheDarkAbsol: That would work if OP didn't have nested everything. I would look into fixing the source where this is coming from, so I get a decent data-structure to work with. Commented May 17, 2014 at 23:37
  • 1
    @elclanrs Oh yeah. I guess a[0].over et al. but yeah, over-nested. Commented May 17, 2014 at 23:39

1 Answer 1

1
object.sort(function(x,y){
    var xx,yy,x1,y1;
    for(var i in x[0]){xx=x[0][i];break;}
    for(var i in y[0]){yy=y[0][i];break;}
    x1=Math.abs(xx.over-xx.under);
    y1=Math.abs(yy.over-yy.under);
    return x1===y1?0:x1>y1?1:-1;
});
Sign up to request clarification or add additional context in comments.

1 Comment

Thank's CrossUI, it's perfect. A bit disappointed with the quickdownvoters here though. I don't think at all this could be solved with the example mentioned above. Besides I offered it myself, which means I had done the research, proved it and it didn't work. Thanks Again CrossUi!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.