繁体   English   中英

如果包含特定单词,则从数组返回匹配项

[英]Return matches from array if contains specific words

我有一个包含几个国家的数组,后跟一个选项和一个数字。

0“UK One 150”

1“瑞士二十七”

2“中国二120”

3“瑞士一号45”

4“中国一号90”

5“UK Two 50”

这是我使用xpath获取数组的方法:

    var iterator = document.evaluate('//xpath/li[*]', document, null, XPathResult.UNORDERED_NODE_ITERATOR_TYPE, null);

try {
  var thisNode = iterator.iterateNext();
  var arrayList = [];

  while (thisNode) {
    arrayList.push(thisNode.textContent); 
    thisNode = iterator.iterateNext();
  }

  for (var i = 0; i < arrayList.length; i++) {
    console.log(arrayList[i]);
  }   
} catch (e) {
  dump('Error' + e);
}
arrayList

我想对这个数组做的是整理并仅返回匹配。 例如,我希望它只返回英国和中国,所以数组看起来像这样。

0“UK One 150”

1“中国二120”

2“中国一号90”

3“英国两个50”

你可以借助sort() filter()regex

我所做的是首先过滤包含UKChina所有元素。

现在在这个已过滤的数组上,我需要使用正则表达式捕获数字并按降序对它们进行排序。

 let arr =[ "UK One 150 ", "Switzerland Two 70 ", "China Two 120 ", "Switzerland One 45 ", "China One 90 ", "UK Two 50 ", ]; let op = arr.filter(e=> /(UK|China)/gi.test(e)) .sort((a,b)=>{a.match(/\\d+/g) - b.match(/\\d+/g)} ); console.log(op); 

您可以使用正则表达式过滤数组,然后对数值进行排序。

 let data =["UK One 150 ","Switzerland Two 70 ","China Two 120 ","Switzerland One 45 ","China One 90 ","UK Two 50 "], result = ((arr) => data.filter(s => new RegExp(arr.join('|'), 'ig').test(s)))(['UK', 'China']) .sort((a,b)=> +a - +b); console.log(result); 

您可以使用Schwartzian变换的形式通过提取国家/地区的名称以及使用array.map()和regex的数字来“装饰”数据。

现在,您可以按国家/地区进行过滤,按数字排序,然后使用其他地图提取str。

 const arr =[ "UK One 150 ", "Switzerland Two 70 ", "China Two 120 ", "Switzerland One 45 ", "China One 90 ", "UK Two 50 ", ]; const pattern = /^(\\S+)\\D+(\\d+)/; const requestedCounteries = new Set(['UK', 'China']); const result = arr .map(str => str.match(pattern)) // ['UK One 150 ', 'UK', '150'] .filter(([,country]) => requestedCounteries.has(country)) .sort(([,,a], [,,b]) => +b - +a) .map(([str]) => str); console.log(result); 

暂无
暂无

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

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