排序数组在对象:Javascript

Sort Arrays in Object: Javascript

本文关键字:Javascript 对象 数组 排序      更新时间:2023-09-26

我有一个包含不同键的对象&

Obj = {
    adj_qty :[10,50], //With close to 50k elements.
    attr_no :["DNF","DNF"],
    qty :["10","50"],
    art_code :["8903ABC4793","8903328757534"],
    cost :[377.95,241.75]
}

现在我想对所有数组的键art_code进行排序。

是否有最好的方法来排序这类数组?

:每个数组大约有50k数组元素。所以我用这种方式将所有这些都组织在单个对象中,而不是数组中的对象。

谢谢,致意。

var sortStack = []
  ,       len = Obj.art_code.length
  ;
// Sort by art_code, storing the sorting results
Obj.art_code.sort( function( a, b ){
    var res = (a>b)?-1:1; // This controls the sorting order
    sortStack.push( res );
    return res;
});
// sort everything else in the same order
for( var n in Obj ){
    if( !Obj.hasOwnProperty( n ) || ( n === 'art_code' ) ){ continue; }
    var ary = sortStack.slice();
    // sort anything that is an array of the same length
    Obj[n].sort
      && ( Obj[n].length === len )
      && Obj[n].sort( function(){ return ary.shift(); } );
}