[英]sort array of objects based on a string
I have a string
and array
like this:我有一个这样的
string
和array
:
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.我想根据
string
从头到尾对array
进行排序。
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!祝你好运!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.