1

I have an array with objects, and I want to sort them by name :

myArray = [{name: 'name10'}, {name: 'name9'}, {name: 'name1'}, {name: 'name3'}]

When I apply the sort method like this

myArray.sort((a, b) => (a.name > b.name) ? 1 : ((b.name > a.name) ? -1 : 0));

it gives me 10 just after 1

myArray = [{name: 'name1'}, {name: 'name10'}, {name: 'name3'}, {name: 'name9'}]

Can I fix this ?

1
  • Your "1" should be "01" Commented Aug 21, 2020 at 15:47

2 Answers 2

2

You could take String#localeCompare with options.

const array = [{ name: 'name10' }, { name: 'name9' }, { name: 'name1' }, { name: 'name3' }];

array.sort(({ name: a }, { name: b }) =>
    a.localeCompare(b, undefined, { numeric: true, sensitivity: 'base' })
);

console.log(array);
.as-console-wrapper { max-height: 100% !important; top: 0; }

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

1 Comment

This is a great solution
1

If you want to sort the names by the number at the end:

myArray = [{name: 'name10'}, {name: 'name9'}, {name: 'name1'}, {name: 'name3'}]
myArray.sort((a,b) => {
     let aNumber = a.name.match(/\d+$/), bNumber = b.name.match(/\d+$/);
     if(aNumber && bNumber)
          return parseInt(aNumber[0]) - parseInt(bNumber[0]);
     else
          return a-b;
});
console.log(myArray);

9 Comments

Undervoter, you need to explain...
why it has been downvoted?
@MajedBadawi try putting one of the fields to "name" only . it will respond with error
@yash can see above comment.
@MajedBadawi you don't need [0]
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.