Ranking an array of string rows by score - javascript

I need to create a new array of string rows from an input one. The input array contains just a country name followed by its score. My goal is to recreate this array by adding one more value, which is the rank that the country will appear. Please, check out my skeleton code below.
<!DOCTYPE html>
<html><head><meta charset="UTF-8"></head>
<body>
<button type="button" onclick="myRankFunction( ['AFG\t3,416', 'AUS\t1,414', 'BRA\t2,073', 'JPN\t1,316'] )">Rank</button>
<script>
/*
* The function must return a new rowlist in the format:
* Rank[TAB]Country[TAB]Score
* - notice that the input rowlist DOESN'T contain the "Rank" part in the begining of the row;
* - Rank is an integer number which represents the country's position in the ranking;
* - Score is a float number; more Score means better Rank.
*/
function myRankFunction(rowlist)
{
var newrowlist = [];
var s1 = [], s2 = [];
for(i = 0; i < rowlist.length; i++)
{
s1 = rowlist[i].split("\t");
for(j = 0; j < rowlist.length; j++)
{
// ignores the current row
if(i == j)
{
continue;
}
s2 = rowlist[j].split("\t");
if( s1[1] > s2[1] )
{
}
else if( s1[1] < s2[1] )
{
}
else
{
}
}
}
return newrowlist;
}
</script>
For the example above, the function should return:
['1[TAB]AFG[TAB]3,416',
'2[TAB]BRA[TAB]2,073',
'3[TAB]AUS[TAB]1,414',
'4[TAB]JPN[TAB]1,316']

['AFG\t3,416', 'AUS\t1,414', 'BRA\t2,073', 'JPN\t1,316'].sort(function(a,b){
//retrieving the rank by splitting the entry and return true or false to the sort callback function
//in order to sort by rank 1,2,3 ...
return(a.split('\t')[1]<b.split('\t')[1])
}).map(function(e,i){
//creating a new array from the sorted array
//adding the rank (using the index) - have to add 1, since index starts at 0
return (i+1)+"\t"+e;
})

Related

Google Script: Multiple conditions per unique ID

The script would count the number of times all VIN numbers are repeated & if all parts have arrived for that VIN Number (Car).
In example, if the VIN number is repeated 5 times then that means there are five parts going to arrive, so then the next step would be to check the arrived column for such VIN if there are 5 "Yes" values then
(VIN number repeated) 5/5 (Number of "Yes" values)
would trigger it to change the [Master] tab Parts Order column to "Yes" for that particular VIN number.
User would manually update the [Parts] tab, arrived column with either "Yes" or leave blank. (If blank then part has not arrived.)
See link for google sheet Template:
https://docs.google.com/spreadsheets/d/1wlGV_QCWpRwmI5FWiOli6lXuzRATy_Goygp3lhtm-Ek/edit?usp=sharing
My attempt:
Special function to get the last value of a column:
function getLastRowSpecial(range){
var rowNum = 0;
var blank = false;
for(var row = 0; row < range.length; row++){
if(range[row][0] === "" && !blank){
rowNum = row;
blank = true;
}else if(range[row][0] !== ""){
blank = false;
};
};
return rowNum;
};
Here I was able to count the number of times each VIN Number appears, but I was unable to count the number of "Yes" values for each unique VIN number. This needs to be dynamic. My approach at the end was not dynamic. Regarding in particular the, var number
Main Script:
/** ---------------------- SPREAD SHEETS ---------------------- **/
var masterS = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Master");
var partS = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Parts");
/** ----------------- Selecting Range of Cells ----------------- **/
/** ----- Parts Spread Sheet ----- **/
/** VIN to Match */
var vinPartOrderRangeP = partS.getRange("C5:C");
var vinPartValuesP = vinPartOrderRangeP.getValues();
var columnCheckPartVINP = getLastRowSpecial(vinPartValuesP);
var partVINDataRangeP = partS.getRange(5, 3, columnCheckPartVINP, 1);
var partsVinSetP = partVINDataRangeP.getValues();
/** Part Arrived */
var partOrderedRangeP = partS.getRange("N5:N");
var partOrderedValuesP = partOrderedRangeP.getValues();
var partOrderedValuesCorrectLengthP = partOrderedValuesP.splice(0,partsVinSetP.length);
/** Combining VINs with Parts Arrived */
var vinPartsArrivedP = [];
vinPartsArrivedP.push(partsVinSetP,partOrderedValuesCorrectLengthP);
/** ----- Master Spread Sheet ----- **/
/** VIN to Match */
var vinPartOrderRangeM = masterS.getRange("B5:B");
var vinPartValuesM = vinPartOrderRangeM.getValues();
var columnCheckPartVINM = getLastRowSpecial(vinPartValuesM);
var partVINDataRangeM = masterS.getRange(5, 2, columnCheckPartVINM, 1);
var partsVinSetM = partVINDataRangeM.getValues();
/** Part Arrived */
var partPastRangeM = masterS.getRange("I5:I");
var partPastValuesM = partPastRangeM.getValues();
/** ---- For-Loop getting Number of Parts that need to Arrive ---- **/
var vinNumber = [], arrivalPartsRequired = [], prev;
for (var i = 0; i < vinPartsArrivedP[0].length; i++) {
if (vinPartsArrivedP[0][i][0] !== prev) {
vinNumber.push(vinPartsArrivedP[0][i][0]);
arrivalPartsRequired.push(1);
} else {
arrivalPartsRequired[arrivalPartsRequired.length - 1]++;
}
prev = vinPartsArrivedP[0][i][0];
}
console.log('[' + vinNumber[0] + ']','[' + arrivalPartsRequired[0] + ']')
/**
* Now we can say arrivalPartsRequired has the number of Yes's we need
* per each VIN number.
**/
console.log(vinPartsArrivedP[0][3][0])
var number = 0;
var number2 = 0;
var number3 = 0;
var number4 = 0;
var number5 = 0;
for (var j = 0; j < partsVinSetM.length; j++) {
};
for (var k=0; k<vinPartsArrivedP[0].length; k++){
if(vinNumber[0] == vinPartsArrivedP[0][k][0]){
number++
for (var i=0; i<partOrderedValuesP[0].length; i++){
for (var j = 0; j < partOrderedValuesP[0].length; j++) {
if (partOrderedValuesP[i][j] == 'Yes') {
console.log(i);
return i+1;
}
}
return -1;
}
}
if(vinNumber[1] == vinPartsArrivedP[0][k][0]){
number2++
}
if(vinNumber[2] == vinPartsArrivedP[0][k][0]){
number3++
}
if(vinNumber[3] == vinPartsArrivedP[0][k][0]){
number4++
}
if(vinNumber[4] == vinPartsArrivedP[0][k][0]){
number5++
}
};
console.log(number);
console.log(number2);
console.log(number3);
console.log(number4);
console.log(number5);
I believe your goal as follows.
You want to retrieve the values from the columns "C" and "N" from "Parts" sheet, and want to check whether the number of same VIN # at the column "C" and the number of yes at the column "N".
When both numbers are the same, you want to put yes to the column "I" of "Master" sheet.
You want to achieve this using Google Apps Script.
In this case, in order to achieve your goal, how about the following flow?
Retrieve values from "Parts" sheet.
Create an object for checking the number of VIN # and yes.
Create an array for putting to the "Master" sheet.
Put the values to the "Master" sheet.
When this flow is reflected to a sample script, it becomes as follows.
Sample script:
function sample() {
// 1. Retrieve values from "Master" sheet.
var masterS = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Master");
var valuesOfParts = partS.getRange("C5:N" + partS.getLastRow()).getValues();
// 2. Create an object for checking the number of `VIN #` and `yes`.
var obj = valuesOfParts.reduce((o, [c,,,,,,,,,,,n]) => {
if (o[c]) {
o[c].c += 1;
if (n == "yes") o[c].yes += 1;
} else {
o[c] = {c: 1, yes: n == "yes" ? 1 : 0};
}
return o;
}, {});
// 3. Create an array for putting to the "Master" sheet.
var partS = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Parts");
var rangeOfMaster = masterS.getRange("B5:B" + masterS.getLastRow());
var valuesOfMaster = rangeOfMaster.getValues().map(([b]) => [obj[b] && obj[b].c == obj[b].yes ? "yes" : ""]);
// 4. Put the values to the "Master" sheet.
rangeOfMaster.offset(0, 7).setValues(valuesOfMaster);
}
References:
reduce()
map()

I want to write a Google App Script to automate calculating late days in Google Sheet

I want to write a code that automate the late days calculation. Here is how it should work
If the score of date after (ex: date 10) - score of day before (date 9)> 0 => the score of date after (120) will be assigned "late for 3 days"
On the other hand, that date after will keep looking and substracting from the next date before until it gets "> 0" result.
The example is illustrated in attached image.
Here is the code that I currently have and it didnt work:
function myFunction() {
var app = SpreadsheetApp;
var activeSheet = app.geActiveSpreadsheet().getActiveSheet();
for (var i=2; i <= 8; i++){
var scoreafterCell = activeSheet.getRange(i;2).getValue();
var scorebeforeCell= activeSheet.getRange(i++;2).getValue();
scoreDiff= scoreafterCell- scorebeforeCell;
if(scoreDiff > 0) {
activeSheet.getRange(i,3).setValue(3);
} else for (var k=0; k++) {
do {
lateDays= k+=3;
activeSheet.getRange(i,3).setValue(lateDays);
}
while (scoreDiff = 0);
}
}
}
Hope to have some inputs soon since this is very important for my work!!! Thank you.
Since there is no clear pattern above, I did a hack to achieve what you want. This only checks the scores and doesn't check the dates as lateDays won't be dependent on that.
Please see the code below.
function generateLateDays() {
var activeSheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
var lastRow = activeSheet.getLastRow();
var scores = activeSheet.getRange('B2:B' + lastRow).getValues().flat();
var output = activeSheet.getRange('C2:C' + lastRow);
var lateDays = [];
while(scores.length > 0) {
// get how many occurences does the first element have
occurence = scores.filter(value => value === scores[0]).length;
// remove current item in advance, we will only be checking number of occurences
// exact value will not be checked, so scores should be in descending order
scores = scores.filter(score => score !== scores[0]);
// contains per score late days
var temp = [];
for(var j = 0; j < occurence; j++) {
if(scores.length > 0) {
// e.g. 3 duplicates will make temp 3, 4, 5
temp.push(j + 3);
}
else {
// when last element is up, push 0
temp.push(0);
}
}
// e.g. temp reverse will be 5, 4, 3
temp.reverse();
// add to final output
lateDays.push(temp);
}
// convert 2d array to 1d array
lateDays = lateDays.flat();
for(var i = 0; i < lateDays.length; i++) {
// convert all elements into an array for setValues
lateDays[i] = [].concat(lateDays[i]);
}
output.setValues(lateDays);
}
Note that this will work only on the order your sample sheet works. I haven't tried doing it ascending. Since your sheet score descending, I made this to work that way.
If you have any questions, feel free to ask below.
Below is my suggested answer. Check it out:
function getLateDates() {
var activeSheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
var scores = activeSheet.getRange('B2:B10').getValues().flat();
var output = activeSheet.getRange('D2:D10');
/**
* Set LateDates[_] as array of 3,
* except the last value = 0 ( at t = 0 )
*
*/
let LateDates = [
...Array.from({ length: scores.length - 1 }).map((x) => 3),
0,
];
/** Check the diff of current score with each of the next score,
* if diff > 0 --> break --> LateDates[current] = 3
* if diff = 0 --> +1 to LateDates[current], and continue w the next score
*
*/
for (var current = 0; current < scores.length; current++) {
for (var next = current + 1; next < scores.length; next++) {
let d = scores[current] - scores[next];
if (d > 0) {
break;
} else {
LateDates[current]++;
}
}
}
/**
* Reduce the LateDates to fit setValues format
*/
let result = LateDates.reduce((a,c)=> ([...a,[c]]),[])
output.setValues(result)
//console.log('result', result);
}
Notice I'm using your date order (descending).
If it's ascending, switch 0 to top of LateDates[] instead:
let LateDates = [
0,
...Array.from({ length: scores.length - 1 }).map((x) => 3),
];

Ignoring empty cells in Google Sheets custom script

I am trying to create a formula to calculate Net Promoter Score on Google Sheets. I have the formula working but only when I specify the exact range. My issue is that this specific sheet will grow with data over time and I do not want to have to keep reselecting the range. What I want to do is select the entire row and just let it auto-update the NPS score. My issue with this approach is every empty cell is considered a zero which is screwing up my percentages. How can I make my function ignore the empty cells???
Here is my attempt:
/**
This is a custom formula that calculates the Net Promoter Score.
#customFunction
*/
function NPS(numArr) {
var detractors = new Array();
var passive = new Array();
var promoters = new Array();
var i = 0;
for (i = 0; i < numArr.length; i++) {
if (isNaN(numArr[i])) {
console.log(numArr[i]);
} else {
if (numArr[i] >= 9) {
promoters.push(numArr[i]);
} else if (numArr[i] === 7 || numArr[i] === 8) {
passive.push(numArr[i]);
} else if (numArr[i] <= 6) {
detractors.push(numArr[i]);
}
}
}
var promoPercentage = promoters.length / numArr.length;
var detractorsPercentage = detractors.length / numArr.length;
return (promoPercentage - detractorsPercentage) * 100;
}
You can use JavaScript filter [1] function to filter the empty values from the array you're getting (numArr). Also, notice that you're selecting a range of cells so the argument will be a 2D array [2], where each value is a "row" array filled with the column values for that row, in case you just want the first value of each row (for a one column range like A1:A25) you need to access the first element of each "row" array to get the actual value:
function NPS(numArr) {
var detractors = new Array();
var passive = new Array();
var promoters = new Array();
var i = 0;
//Filter empty elements
numArr = numArr.filter(function(element) {
return element[0] !== '';
})
for (i = 0; i < numArr.length; i++) {
if (isNaN(numArr[i][0])) {
console.log(numArr[i][0]);
} else {
if (numArr[i][0] >= 9) {
promoters.push(numArr[i][0]);
} else if (numArr[i][0] === 7 || numArr[i][0] === 8) {
passive.push(numArr[i][0]);
} else if (numArr[i][0] <= 6) {
detractors.push(numArr[i][0]);
}
}
}
var promoPercentage = promoters.length / numArr.length;
var detractorsPercentage = detractors.length / numArr.length;
return (promoPercentage - detractorsPercentage) * 100;
}
[1] https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter
[2] https://developers.google.com/apps-script/guides/sheets/functions#arguments

How to automate randomizing 46 names to create 46 x 6 unique rows and columns in Google sheet?

I am working with automation in Google sheet. Can you help me?
This problem is for sending surveys to 46 people. Each people needs to rate 5 people from those 46 people.
Requirements:
1. 1 rater, for 5 uniques ratees
2. No duplicate name per row (it should be 6 unique names in a row)
3. No duplicate name per column (it should be 46 unique names per column)
Expected output is for us to create 46x6 random names with no duplicates in row and columns.
-
-
Flow:
If a unique matrix across and below can be created, then it's values can be used as keys to the actual name array.
Create a 2D number array with length = number of rows
Loop through required number of columns and rows
Create a temporary array (tempCol) to store current column data
Fill the array with random numbers
Use indexOf to figure out if any random numbers are already present in the currentrow/ current column, if so, get a new random number.
In random cases, where it's impossible to fill up the temporary column with unique random numbers across and below, delete the temporary column and redo this iteration.
Snippet:
function getRandUniqMatrix(numCols, numRows) {
var maxIter = 1000; //Worst case number of iterations, after which the loop and tempCol resets
var output = Array.apply(null, Array(numRows)).map(function(_, i) {
return [i++]; //[[0],[1],[2],...]
});
var currRandNum;
var getRandom = function() {
currRandNum = Math.floor(Math.random() * numRows);
}; //get random number within numRows
while (numCols--) {//loop through columns
getRandom();
for (
var row = 0, tempCol = [], iter = 0;
row < numRows;
++row, getRandom()
) {//loop through rows
if (//unique condition check
!~output[row].indexOf(currRandNum) &&
!~tempCol.indexOf(currRandNum)
) {
tempCol.push(currRandNum);
} else {
--row;
++iter;
if (iter > maxIter) {//reset loop
iter = 0;
tempCol = [];
row = -1;
}
}
}
output.forEach(function(e, i) {//push tempCol to output
e.push(tempCol[i]);
});
}
return output;
}
console.info(getRandUniqMatrix(6, 46));
var data1d = data.map(function(e){return e[0]});
var finalArr = getRandUniqMatrix(6, 46).map(function(row){return row.map(function(col){return data1d[col]})});
destSheet.getRange(1,1,finalArr.length, finalArr[0].length).setValues(finalArr);
The OP wants to create a review matrix in which the names of the reviewed employees are chosen at random, the reviewer cannot review themselves, and the matrix is completed for 46 employees.
Based on previous code, this version builds an array of employee names for each row, in which the name of the reviewer is not included in the array. Five names are chosen at random and applied to the reviewer. The loop then repeats through each of the 46 employees.
For example, in the first round of reviews, "name01" is omitted from the array of employees from which the "reviewees" are randomly chosen. In the second round, "name01" is included, but "name02" is excluded from the array of employees. And so on, such that in each case, the array of employees used for the random selection of five reviews is always 45 names in length, and excludes the name of the reviewer.
The random selection of names to be rated does not ensure an equal and even distribution of reviews among employees. Though each employee will conduct 5 reviews, some employees are reviewed more than 5 times, some less than 5 times, and (depending on the alignment of the sun, the moon and the stars) it is possible that some may not be selected for review.
function s05648755803(){
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheetname = "Sheet3";
var sheet = ss.getSheetByName(sheetname);
// some variables
var randomcount = 30; // how many random names
var rowstart = 7; // ignore row 1 - the header row
var width = 5; // how many names in each row - 1/rater plus 5/ratee
var thelastrow = sheet.getLastRow();
//Logger.log("DEBUG:last row = "+thelastrow)
// get the employee names
var employeecount = thelastrow-rowstart+1;
//Logger.log("DEBUG: employee count = "+employeecount);//DEBUG
// get the data
var datarange = sheet.getRange(rowstart, 1, thelastrow - rowstart+1);
//Logger.log("DEBUG: range = "+datarange.getA1Notation());//DEBUG
var data = datarange.getValues();
//Logger.log("data length = "+data.length);
//Logger.log(data);
var counter = 0;
var newarray = [];
for (c = 0;c<46;c++){
counter = c;
for (i=0;i<data.length;i++){
if(i!=counter){
newarray.push(data[i]);
}
}
//Logger.log(newarray);
var rowdata = [];
var results = selectRandomElements(newarray, 5);
Logger.log(results)
rowdata.push(results);
var newrange = sheet.getRange(rowstart+c, 3, 1, 5);
newrange.setValues(rowdata);
// clear the arrays for the next loop
var newarray=[];
var rowdata = []
}
}
/*
// selectRandomElements and getRandomInt
// Credit: Vidar S. Ramdal
// https://webapps.stackexchange.com/a/102666/196152
*/
function selectRandomElements(fromValueRows, count) {
var pickedRows = []; // This will hold the selected rows
for (var i = 0; i < count && fromValueRows.length > 0; i++) {
var pickedIndex = getRandomInt(0, fromValueRows.length);
// Pick the element at position pickedIndex, and remove it from fromValueRows. See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice
var pickedRow = fromValueRows.splice(pickedIndex, 1)[0];
// Add the selected row to our result array
pickedRows.push(pickedRow);
}
return pickedRows;
}
function getRandomInt(min,
max) { // From https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min)) + min;
}
Screenshot#1
Screenshot#2
Try this. Satisfies all the three requirements.
HTML/JS:
<html>
<title>Unique Employees</title>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
</head>
<table id="survey_table" border="1" width="85%" cellspacing="0">
<thead>
<th>Rater</th>
<th>Ratee1</th>
<th>Ratee2</th>
<th>Ratee3</th>
<th>Ratee4</th>
<th>Ratee5</th>
</thead>
<tbody id="table_body">
</tbody>
</table>
<script type="text/javascript">
function arrayRemove(arr, value) {
return arr.filter(function(ele) {
return ele != value;
});
}
function getRandomInt(rm_row, rm_col) {
var temp_arr = [];
for (var k = 1; k <= 46; k++) {
temp_arr.push(k);
}
for (var k = 0; k < rm_row.length; k++) {
temp_arr = arrayRemove(temp_arr, rm_row[k]);
}
for (var k = 0; k < rm_col.length; k++) {
temp_arr = arrayRemove(temp_arr, rm_col[k]);
}
var rand = temp_arr[Math.floor(Math.random() * temp_arr.length)];
return rand;
}
function exclude_num(row_unq, col_unq) {
var rand_int = getRandomInt(row_unq, col_unq);
if (!row_unq.includes(rand_int) && !col_unq.includes(rand_int)) {
arr_row.push(rand_int);
return rand_int;
} else {
return exclude_num(arr_row, arr_cols);
}
}
for (var i = 1; i <= 46; i++) {
var arr_row = [];
arr_row.push(i);
var table_html = '<tr id="Row' + i + '">';
for (var j = 1; j <= 6; j++)
{
if (j == 1) {
table_html += '<td class="Column' + j + ' cells_unq">' + i + '</td>';
} else {
var arr_cols = []
$('.Column' + j).each(function() {
arr_cols.push(Number($(this).text()));
});
var num = exclude_num(arr_row, arr_cols);
table_html += '<td class="Column' + j + ' cells_unq">' + num + '</td>';
}
}
table_html += '</tr>';
var row_html = $('#table_body').html();
$('#table_body').html(row_html + table_html);
}
$('.cells_unq').each(function() {
temp_text = $(this).text();
$(this).text('Name' + temp_text);
});
</script>
<style type="text/css">
td {
text-align: center;
}
</style>
</html>

find top k elements in array

I have an array in the format:
var series = [[horse,1],[cat,2],[dog,4],[dragon,4],[cow,6]]
In order to find the top 3 elements based on the 2nd parameter I sort the array. So for this purpose I use the code below:
series.sort( function(a,b) {
if (a[1] === b[1]) {
return 0;
}
else {
return (a[1] < b[1]) ? 1 : -1;
}
});
Which works fine. Then If I want to find the top 3 I can always select [0,2]. However, if the 4th value equals the the 3th then I miss it. In this case if I ask for the top 3 the output should be [[horse,1],[cat,2],[dog,4],[dragon,4] because dragon and dog have equal value (4). So, I wonder is there some library I could use out of the box or some efficient algorithm to return the top 3 values which does not necessarily mean returning top 3 element arrays?
Just build a list:
var top = [];
top.push(series[0]);
top.push(series[1]);
for (var i = 2; i < series.length && series[i][1] == series[2][1]; ++i)
top.push(series[i]);
To generalize that (a little):
function top(series, k) {
var top = [];
for (var i = ; i < k - 1; ++i)
top.push(series[i]);
for (; i < series.length && series[k-1][1] == series[i][1]; ++i)
top.push(series[i]);
return top;
}
var series = [["horse",1],["cat",2],["dog",4],["dragon",4],["cow",6]]
num = 3;
var arr = [];
for(var i=0; i<series.length; i++)
{
var curr = series[i][1];
var next = series[i][1];
if(i<num)
{
arr.push(series[i]);
}
else if(curr==next)
{
arr.push(series[i]);
break;
}
}
console.log(arr);
So I would make a second array (length of 3) and loop through the initial array. When The first three items should be automatically added to the array. Then as we loop through the first array and find values higher than the lowest value we remove the lowest value and place the new item in the new array in its proper place.
var series = [[horse,1],[cat,2],[dog,4],[dragon,4],[cow,6]];
function top3(a){
// Create a new Array to hold the top values
var top = [a[0], a[1], a[2]]; // Initialize it with the first three items
for(var i=3;i<a.length;i++){
/* Find the minimum value and its position */
var min = top[0][1];
var min_pos = 0;
for(var e=1;e<3;e++){
if(top[e][1]<min){
min = top[e][1];
min_post = e;
}
}
/* If larger than the top arrays minimum */
if( a[i][1] > min ){
/* remove the top arrays min */
top.splice(min_pos, 1);
}
/* Add the new item into the top array */
top.push(a[i]);
}
/* Now our "top" array has the items with the top 3 values, if you want them sorted use a bubble sort here, if not just return "top" */
bubbleSortByIndex(a, 1); // Sorts by the second item in an array or arrays
return top;
};
/*
Bubble Sort Algorythm adapted from http://en.wikipedia.org/wiki/Bubble_sort
*/
function bubbleSortByIndex(a, i){
var swapped;
do {
swapped = false;
for(var e=1;e<a.length-1;e++){
if( a[e-1][i] > A[e][i]){
swapped = true;
var temp = a[e-1];
a[e-1] = a[e];
a[e] = temp
}
}
} while (swapped);
return a;
}
top3(series);
This leaves the original array in tact and finds the top three items only, and sorts those. If you wanted the entire original array sorted then just call bubbleSortByIndex(series, 1) and ignore the whole "top3()" function.

Categories