繁体   English   中英

根据字符串对对象数组进行排序

[英]sort array of objects based on a string

我有一个这样的stringarray

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' },

];

我想根据string从头到尾对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' },

请注意,如果存在较长版本的恶意文本,则它应该紧随其后,正如您在注释元素中看到的那样。

我怎样才能做到这一点?

供您参考的解决方案。

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

这对我来说听起来像是一个家庭作业,所以我不会给你实际的完整代码。

该算法将是:

  1. 遍历数组。
  2. 确定字符串中每个元素的起始索引。
  3. 根据索引值对数组进行升序排序。
  4. 如果有两个索引具有相同的值,则通过将最短的数组元素放在第一位来消除歧义。
  5. 结尾。

祝你好运!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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