javascript - Generate JS array that determines sorted rank -


using complex array (for use case of tabular data displayed in columns , rows) lets have values:

var values = [     [234, 386, 21, 38],     [-23, 58, 106, 0],     [45, -48, 506, 23],     [109, 168, 42, 111] ]; 

what best way return matching array rank values against column in correct (maintained) order? ranked order highest lowest in case.

for example, end result array of:

[     [1, 1, 4, 2],     [4, 3, 2, 4],     [3, 4, 1, 3],     [2, 2, 3, 1] ]; 

note how result sorted vertically column.

i want use large data set, guidance/tips quickest performance aim here.

--

for context: first attempt map original array index values, unsure go there:

var singlecolumn = [234, -23, 45, 109]; (var = 0; < singlecolumn.length; i++) {     singlecolumn[i] = [singlecolumn[i], i]; } 

essentially trick retaining original indices after sort. i've iterated them data structure first, sorted it, , rebuilt 2-dimensional array structure result.

i haven't done checking ensure input well-formed, assumption rows same width first row.

an optimization done transforming raw values data-structure during sort, eliminate pass of array. don't see easy way without losing of conciseness , readability, , pretty small gain.

var values = [      [234, 386, 21, 38],      [-23, 58, 106, 0],      [45, -48, 506, 23],      [109, 168, 42, 111]  ];    function buildranking(arr) {    var result = [];    for(var col = 0; col < arr[0].length; col++) {      //everything inside loop per column        //first use map function turn column array of objects      //each holding value , current index. [{value: 234, index: 1}, etc..]      var sortablestructure = values.map(function(val, i) {        return { value : val[col], index : };      });        //sort function sort sortablestructure in place on values      sortablestructure.sort(function(a, b) {        return b.value - a.value;      });        //now iterate on sortable strucutre      for(var = 0; < sortablestructure.length; i++) {        //this ugly bit makes sure arrays initialized each row needed        if(typeof result[sortablestructure[i].index] === 'undefined')            result[sortablestructure[i].index] = [];         //for current item in sortablestructure, index       //access result element corresponding index        //(the original position of sorted value) , push in        //the current index (sort order) + 1 (to switch zero-based one-based)        result[sortablestructure[i].index].push(i + 1);      }    }    return result;  }    //to provide visible output.  document.write(json.stringify(buildranking(values)).split('],[').join('],<br/>['));


Comments

Popular posts from this blog

how to insert data php javascript mysql with multiple array session 2 -

multithreading - Exception in Application constructor -

windows - CertCreateCertificateContext returns CRYPT_E_ASN1_BADTAG / 8009310b -