-1

I have to sort an array of objects with a number in the name of each objects. Example

const question = [{name:"Question 1 #1", content:"blabla?"}, {name:"Question 1 #3", content:"blabla?"}, {name:"Question 1 #4", content:"blabla?"}, {name:"Question 1 #2", content:"blabla?"}]

How can i ordered them by the number after the #?

  • 1
    Do you expect "Question 1#1" -> "Question 1#3" -> "Question 2#2" -> "Question 2#3" or instead "Question 1#1" -> "Question 2#2" -> "Question 1#3" -> "Question 2#4"? – VLAZ Sep 27 '21 at 13:22
  • 1
    You need to use regex to get the number after the `#`, then it's a matter of sorting it using that number. – Terry Sep 27 '21 at 13:22
  • @VLAZ I expect "Question 1#1" -> "Question 2#2" -> "Question 1#3" -> "Question 2#4" – Haine Thomas Sep 27 '21 at 13:24
  • @Terry what's wring with `.split()`? – VLAZ Sep 27 '21 at 13:26
  • @vlaz I didn't say OP shouldn't use split...? – Terry Sep 27 '21 at 13:29
  • @Terry well, sounds like OP doesn't *need* to use a regex, if `.split()` is also an option. – VLAZ Sep 27 '21 at 13:31
  • @VLAZ Again, that's one of the ways to get a number after the `#`. Not sure why people are being pedantic and reading unnecessarily between the lines of what isn't said. – Terry Sep 27 '21 at 13:35
  • @Terry "need" implies it's a hard requirement. Therefore, what you said is that it cannot be done without regex. One of my pet peeves is throwing regex at anything string-related when there are simpler alternatives. – VLAZ Sep 27 '21 at 13:38
  • @VLAZ You do you ¯\\_(ツ)_/¯ – Terry Sep 27 '21 at 13:39

2 Answers2

0

The simplest way:

function sortFunction( a, b ) {
  const aNumber = parseInt(a.name.split('#')[1]);
  const bNumber = parseInt(b.name.split('#')[1]);
  if ( aNumber < bNumber ){
    return -1;
  }
  if ( aNumber >bNumber ){
    return 1;
  }
  return 0;
}

const question = [{name:"Question 1 #3", content:"blabla?"}, {name:"Question 1 #4", content:"blabla?"}, {name:"Question 1 #1", content:"blabla?"}, {name:"Question 1 #2", content:"blabla?"}]

console.log(question.sort(sortFunction));
Harshit Rastogi
  • 1,996
  • 1
  • 10
  • 19
0

Just split the name on # and access the number after that. Sort the array based on thiis number.

const question = [{name:"Question 1 #1", content:"blabla?"}, {name:"Question 1 #3", content:"blabla?"}, {name:"Question 1 #4", content:"blabla?"}, {name:"Question 1 #2", content:"blabla?"}]
const getNumeric = (name) => Number(name.split('#')[1]?.trim() || 0);
const sortedQuestion = question.sort((a, b) => getNumeric(a.name) > getNumeric(b.name) ? 1 : getNumeric(a.name) === getNumeric(b.name) ? 0 : -1);
console.log(sortedQuestion);
Nitheesh
  • 19,238
  • 3
  • 22
  • 49