0

I have to sort a string array based on the number.

Example

["1.READ","10.CREATE","3.sfg","2.dfd","12.dqwe"];

Desired Result

["1.READ","2.dfd","3.sfg","10.CREATE","12.dqwe"];

My Code

var arr = ["1.READ","10.CREATE","3.sfg","2.dfd","12.dqwe"];
var arr2 = arr.map( a => a.split('.').map( n => +n+100000 ).join('.') ).sort().map( a => a.split('.').map( n => +n-100000 ).join('.') );
console.log(arr);
console.log(arr2);

3 Answers 3

2

You can just split and convert the first element to Number

var arr = ["1.READ", "10.CREATE", "3.sfg", "2.dfd", "12.dqwe"];

var arr2 = arr.sort((a, b) => {
  return Number(a.split(".")[0]) - Number(b.split(".")[0]);
});

console.log(arr2);


The code above will also sort the first variable. If you you only want arr2 to be sorted, you can:

var arr = ["1.READ", "10.CREATE", "3.sfg", "2.dfd", "12.dqwe"];

var arr2 = [...arr]; //Spread the array so that it will not affect the original
arr2.sort((a, b) => {
  return Number(a.split(".")[0]) - Number(b.split(".")[0]);
});

console.log(arr);
console.log(arr2);

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

Comments

2

You could split and take only the first part. Then take the delta for sorting.

var array = ["1.READ", "10.CREATE", "3.sfg", "2.dfd", "12.dqwe"];

array.sort((a, b) => a.split(".")[0] - b.split(".")[0]);

console.log(array);

1 Comment

@NinaScholz as clean as it can be :)
1

Here it is:

var arr = ["1.READ","10.CREATE","3.sfg","2.dfd","12.dqwe"];

arr.sort(function(a, b) {
    return a.split('.')[0] - b.split('.')[0];
});

console.log(arr)
// ["1.READ", "2.dfd", "3.sfg", "10.CREATE", "12.dqwe"]

This answer base on built in array sort function, with customizable compare logic. Check this out for more detail: Javascript Array Sort

Cheers,

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.