0

I have an array as shown below:

var fruits = ['0-2','1-1','12-2','14-2','2-3','21-1','4-1'];

It gives me output like this:

0-2,1-1,12-2,14-2,2-3,21-1,4-1.

I want to sort this array and get output as:

0-2,1-1,2-3,4-1,12-2,14-2,21-1 using JavaScript/jQuery.

I tired using fruits.sort(); but that does not work, any suggestions?

2

2 Answers 2

5

You have to format the input (by removing the hyphen) before comparison to get the expected result:

var fruits = ['0-2','1-1','12-2','14-2','2-3','21-1','4-1'];

fruits.sort(function(a, b){
  a = a.replace('-', '')
  b = b.replace('-', '');
  return a - b;
});
console.log(fruits)

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

Comments

3

You have to pass a compareFunction and split() the string and compare the first element of the array

var fruits = ['0-2', '1-1', '12-2', '14-2', '2-3', '21-1', '4-1'];

fruits.sort((a, b) => a.split('-')[0] - b.split('-')[0]);

console.log(fruits);

Doc: sort()

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.