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:
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.