0

I have an array of objects, like this:

array = [ {userId: 'Y-10'}, {userId: 'Y-1'}, {userId: 'Y-14'}, {userId: 'Y-24'} ];

I need to sort the array by the userId in order. The results should be in this order: 'Y-1','Y-10','Y-14','Y-24'

I tried using a sort like this array.sort((a,b) => ("" + a.userId).localeCompare(b.userId, undefined, {numeric: true}));

But this doesnt work. How can I sort my array to yield the results i'm seeking?

10
  • I tried the one liner, my version of objs.sort((a,b) => (a.last_nom > b.last_nom) ? 1 : ((b.last_nom > a.last_nom) ? -1 : 0)) but this does not work. I think the "-" is throwing it off... Commented Dec 9, 2021 at 16:10
  • (a,b) => +s1.match(/\d+/) > +b.match(/\d+/) might work? Commented Dec 9, 2021 at 16:13
  • Objs.sort((a,b)=>{parseInt(a.userId.split(‘-‘)[1]) - parseInt(b.userId.split(‘-‘)[1])}); Commented Dec 9, 2021 at 16:18
  • That does not work Peter. For example, I get "Y-9" after "Y-2" Commented Dec 9, 2021 at 16:37
  • 1
    @Pd1234 Y-9 should come after Y-2 if you want Y-1 to come before Y-10. --- Please clarify the outputs you want. Commented Dec 9, 2021 at 17:04

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.