Create a text field:
- Edit-->Select the text field-->Properties-->Format tab->Number
- Edit-->Select the text field-->Properties-->Calculate tab-->Click radio button: Custom calculation script-->Edit:
var n1=this.getField("Number2Row1").value;
var n2=this.getField("Number2Row2").value;
var n3=this.getField("Number2Row3").value;
var arr = [n1, n2,n3];
var sorted = arr.slice().sort(function(a,b){return b-a})
var ranks = arr.slice().map(function(v){ return sorted.indexOf(v)+1 });
event.value=ranks[0];
Here: n1, n2 and n3 will get the value from all the text fields will be included in the ranking.
Example of Javascript code for Ranking Array Elements:
Problem:
I need an algorithm to rank elements of an array in Javascript.
Example : I have an array as follows:
[79, 5, 18, 5, 32, 1, 16, 1, 82, 13]
I need to rank the entries by value. So 82 should receive rank 1, 79 rank 2 etc. If two entries have the same value they receive the same rank and the rank for a lower value is raised.
So for this array, the new ranking array would be:
[2, 7, 4, 7, 3, 9, 5, 9, 1, 6]
How can I do this ?
Solution:
var arr = [79, 5, 18, 5, 32, 1, 16, 1, 82, 13];
var sorted = arr.slice().sort(function(a,b){return b-a})
var ranks = arr.slice().map(function(v){ return sorted.indexOf(v)+1 });
Result :
[2, 7, 4, 7, 3, 9, 5, 9, 1, 6]
If you want to be compatible with old browsers, you may have to define a shim for indexOf and for map (note that if you want to do this very fast for very big arrays, you'd better use
for
loops and use an object as map instead of indexOf
).
No comments:
Post a Comment