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