Home > Software design >  Sort an array of object with a string name parameter containing a number [duplicate]
Sort an array of object with a string name parameter containing a number [duplicate]

Time:09-27

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 #?

CodePudding user response:

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));

CodePudding user response:

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);

  • Related