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?

Pd1234
  • 29
  • 5
  • 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... – Pd1234 Dec 09 '21 at 16:10
  • `(a,b) => +s1.match(/\d+/) > +b.match(/\d+/)` might work? – evolutionxbox Dec 09 '21 at 16:13
  • Objs.sort((a,b)=>{parseInt(a.userId.split(‘-‘)[1]) - parseInt(b.userId.split(‘-‘)[1])}); – Peter Dec 09 '21 at 16:18
  • That does not work Peter. For example, I get "Y-9" after "Y-2" – Pd1234 Dec 09 '21 at 16:37
  • Hey try this `const array = [{ userId: 'Y-10' }, { userId: 'Y-1' }, { userId: 'Y-14' }, { userId: 'Y-24' }]; const compare = (a, b) => { const num_a = +a.userId.split('-')[1]; const num_b = +b.userId.split('-')[1]; console.log("pppp ", num_a); if (num_a < num_b) { return -1; } if (num_a > num_b) { return 1; } return 0; } console.log(array.sort(compare));` – Barty Dec 09 '21 at 17:03
  • 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. – evolutionxbox Dec 09 '21 at 17:04
  • @Barty may you post an answer rather than posting large amounts of code in comments? – evolutionxbox Dec 09 '21 at 17:05
  • @evolutionxbox sorry, I meant "Y-9" comes before "Y-2". – Pd1234 Dec 09 '21 at 17:49
  • @PD1234 looks good to me `let array = [{ userId: 'Y-10' }, { userId: 'Y-1' }, { userId: 'Y-14' }, { userId: 'Y-24' }]; array = array.sort((a, b) => parseInt(a.userId.split('-')[1]) - parseInt(b.userId.split('-')[1])); console.log(array); ` [ { userId: 'Y-1' }, { userId: 'Y-10' }, { userId: 'Y-14' }, { userId: 'Y-24' } ] [ { userId: 'Y-1' }, { userId: 'Y-2' }, { userId: 'Y-9' }, { userId: 'Y-10' }, { userId: 'Y-14' }, { userId: 'Y-24' } ] – Peter Dec 09 '21 at 21:24
  • There were two outputs in that block and one had the 2 and the 9 in there. the sort function returns an array which you should assign back to the original array or a new one. – Peter Dec 09 '21 at 21:31

0 Answers0