Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

sort array of objects based on a string

I have a string and array like this:

const speech = 'marcllh 4th reg gh 4th ethth';

const similarityArray = [

  { split: '4th reg' },
  { split: 'reg gh' },
  { split: 'ethth' },
  { split: 'marcllh' },
  { split: '4th reg gh' },
  { split: '4th ethth' },

];

I want to sort the array based on the string from start to end.

So the desired result would be this array:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

{ split: 'marcllh' },
{ split: '4th reg' },
{ split: '4th reg gh' }, // this is the continue of the previous one
{ split: 'reg gh' },
{ split: '4th ethth' }
{ split: 'ethth' },

Note that if a longer version of spited text exist it should come next as you see in the commented element.

How can I do this?

>Solution :

A solution for your reference.

const string = 'marcllh 4th reg gh 4th ethth';

const array = [
 
{ split: '4th reg gh' },
{ split: '4th reg' },
{ split: 'reg gh' },
{ split: 'ethth' },
{ split: 'marcllh' },
{ split: '4th ethth' }

];

array.sort((a,b) => {
  var ia = string.indexOf(a['split']);
  var ib = string.indexOf(b['split']);
  var result = ia - ib;
  if(result == 0){
     result = a['split'].length - b['split'].length;
  }
  return result;
});

console.log(array);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading