Reputation: 663
I'm after parsing a .csv file and turning it into a jQuery array! Now I want to sort the list so that I can read its values in order of ID number (a value within the array). Here is my array:
$.ajax({
url: "path/to/file.csv",
success: function(data) {
var array1 = data.split("\n");
var array2 = new Array();
for (var i = 0; i < array1.length; i++) {
array2.push(array1[i].split(","));
...
}
array is in this format:
[0] = ID, TITLE, NUMBER
[1] = 1, Name1, 0 << ie: [1][0], [1][1], [1][2]
[2] = 2, Name2, 14
[3] = 3, Name3, 25
[4] = 4, Name4, 66
[5] = 5, Name5, 87
[6] =
In order to ignore the first (title) row and the last (empty) row, I use:
if($.isNumeric(array2[i][0])){
//do something
}
else {
//do nothing
}
The rest if the data gets used as required. However, sometimes the files are not in order. I would like to select the row that has ID '1' first, ID '2' next and so on...
[0] = ID, TITLE, NUMBER
[1] = 5, Name5, 87 << ie: [1][0], [1][1], [1][2]
[2] = 2, Name2, 14
[3] = 4, Name4, 66
[4] = 3, Name3, 25
[5] = 1, Name1, 0
[6] =
Is there a way I can sort the array list? Or would I need to read the data to see whats there each time? (i.e. iterate through the list to find out what row my next ID is on)
Upvotes: 1
Views: 139
Reputation: 1785
you can use .sort
function
array1.sort(function(a,b){
return a[0] - b[0];
});
Upvotes: 0
Reputation: 26143
You can use a custom sort, as such...
array2.sort(function(a, b) {
return a[2] - b[2];
});
Upvotes: 1
Reputation: 773
Have you looked at the built-in sort function? You can provide a custom comparator.
var array = [[30, 'test'], [2, 'okay'], [4, 'yeah']];
array.sort(function(a,b) {return a[0] - b[0]});
Ref: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort
Upvotes: 1
Reputation: 6081
jQuery has the sort function
var myArray = [ 3, 4, 6, 1 ];
myArray.sort(); // 1, 3, 4, 6
You can see here for more examples
http://learn.jquery.com/javascript-101/arrays/
but i can't tell you if it works in the array with the format you posted. This should just be a tip, not a solution
Upvotes: 1