Bear with me, I'm still kinda new to javascript.. I am trying to sort a list of save-game codes to be sorted by their first parse of the element.
var vList =["1|846|Doc|2|0|false|", "11|203|Derik|7|3|false|", "21|670|Mike|5|5|true|", "13|11|Ron|0|0|false|", "9|1000|Blood|9|9|true|"];
var vParse;
for (i = 0; i < (vParse.length); i++)
var vParse[i]= vList.split('|');
// then somehow sort all the data based on vParse[0]?
I tried a few sorting submissions from other folks, but I couldn't get it to ignore all the font after the first parse. Could anyone help me please?
Bear with me, I'm still kinda new to javascript.. I am trying to sort a list of save-game codes to be sorted by their first parse of the element.
var vList =["1|846|Doc|2|0|false|", "11|203|Derik|7|3|false|", "21|670|Mike|5|5|true|", "13|11|Ron|0|0|false|", "9|1000|Blood|9|9|true|"];
var vParse;
for (i = 0; i < (vParse.length); i++)
var vParse[i]= vList.split('|');
// then somehow sort all the data based on vParse[0]?
I tried a few sorting submissions from other folks, but I couldn't get it to ignore all the font after the first parse. Could anyone help me please?
Share Improve this question asked Oct 16, 2016 at 22:26 TheBloodSeeker005TheBloodSeeker005 651 silver badge7 bronze badges 2- You just want to sort the array based on the first number before the pipe ? – adeneo Commented Oct 16, 2016 at 22:31
- @adeneo Yes, that's correct – TheBloodSeeker005 Commented Oct 16, 2016 at 22:31
3 Answers
Reset to default 4You can use Array.sort
and just split on the pipe, get the first item, and when subtracting the strings are converted to numbers anyway
var vList =["1|846|Doc|2|0|false|", "11|203|Derik|7|3|false|", "21|670|Mike|5|5|true|", "13|11|Ron|0|0|false|", "9|1000|Blood|9|9|true|"];
vList.sort(function(a,b) {
return a.split('|')[0] - b.split('|')[0];
});
console.log(vList)
Try some like that:
vList.sort( function( a, b ) {
return parseInt( a.split( '|' )[ 0 ] ) - parseInt( b.split( '|' )[ 0 ] );
} );
You can read more about sort, split and parseInt methods.
How about this
vList.map(function(el){return {sortBy : parseInt(el.split('|')[0]), original : el}}).sort(function(a,b){return a.sortBy - b.sortBy}).map(function(el){return el.original})