简体   繁体   中英

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:

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

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

This sounds like a homework to me, so I won't give you the actual complete code for this.

The algorithm would be to:

  1. Iterate through the array.
  2. Determine the starting index of each of the elements in the string.
  3. Sort the array based on the index values, in ascending order.
  4. If there are two indexes with the same value, disambiguate by putting the shortest array element first.
  5. End.

Good luck!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM