5

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?

2
  • You just want to sort the array based on the first number before the pipe ? Commented Oct 16, 2016 at 22:31
  • @adeneo Yes, that's correct Commented Oct 16, 2016 at 22:31

3 Answers 3

4

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)

Sign up to request clarification or add additional context in comments.

Comments

1

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.

2 Comments

Due to javascript type coercion, in this case '-' on strings, the parseInt's not required.
@Keith, sure, I just thought that parseInt method is more obvious for beginner
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.