Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
375 views
in Technique[技术] by (71.8m points)

javascript - jQuery: Sort results of $.each

The only examples I have been able to find of people using $.each are html samples, and it's not what I want. I have the following object:

var obj = {
    obj1: 39,
    obj2: 6,
    obj3: 'text'
    obj4: 'text'
    obj5: 0
};

I loop through the object like so:

$(array).each(function(index, value) {
    // ...
});

I want to sort by obj3 and obj4. Preferrably not using an asynchronous method, how can I sort the results before (or during) output? (I also don't want to loop through this twice, as there could be hundreds at any given time.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
var array = {
    obj1: 39,
    obj2: 6,
    obj3: 'text'
    obj4: 'text'
    obj5: 0
};

is not an array (its name notwithstanding). It is an object. The idea of sorting by obj3 and obj4 doesn't really make sense.

Now, if you were to convert this object to an array of objects, you could sort that array with the array.sort method.

var array = [
    { obj1: 39,
      obj2: 6,
      obj3: 'text'
      obj4: 'text'
      obj5: 0
    },{ obj1: 40,
      obj2: 7,
      obj3: 'text2'
      obj4: 'text3'
      obj5: 0
    }
];

array.sort(function(a, b) {

    var textA = a.obj3.toLowerCase();
    var textB = b.obj3.toLowerCase();

    if (textA < textB) 
       return -1; 
    if (textA > textB)
       return 1;
    return 0; 
});

and of course to sort by a numeric property, it'd simply be:

array.sort(function(a, b) {
    return a.obj1 - b.obj1;
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...