简体   繁体   English

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

[英]sort array of objects based on a string

I have a string and array like this:我有一个这样的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' },

];

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:该算法将是:

  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!祝你好运!

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

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