TheBloodSeeker005 TheBloodSeeker005 - 1 month ago 5
Javascript Question

Javascript: Sort by first characters of an an array

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?

Answer

You 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)