Trying to sort a custom JavaScript object

后端 未结 5 1046
时光说笑
时光说笑 2021-01-01 04:18

I\'m not too good at JS, but have survived thus far. I\'m creating a sort-of complex JS object and wanting to sort it. The object\'s structure looks like this:

<         


        
5条回答
  •  灰色年华
    2021-01-01 05:03

    Something like this works well, and you can easily define a function to wrap around it and sort jQuery objects given the comparison attribute:

        var $jobj = jQuery( '.jcss' ); // your selector here
        var $jarr = [];
    
        $jobj.each( function () {
            $jarr.push( jQuery( this ) );
        } );
    
        $jarr.sort( function ( a, b ) {
            var attr = {}; // your comparison attribute here
            attr.a = parseInt( a.data( 'priority' ) || 0 );
            attr.b = parseInt( b.data( 'priority' ) || 0 );
            return attr.a < attr.b ? -1 : attr.a > attr.b ? 1 : 0;
        } );
    
        $jobj = jQuery( jQuery.map( $jarr, function ( obj, i ) {
            return obj[0];
        } ) );
    
        // whatever you need to do here
        $jobj.css( { 'text-decoration': 'blink' } );
    

提交回复
热议问题