[英]Return matches from array if contains specific words
I have an array that contains several countries followed by an option and a number. 我有一个包含几个国家的数组,后跟一个选项和一个数字。
0 " UK One 150 " 0“UK One 150”
1 " Switzerland Two 70 " 1“瑞士二十七”
2 " China Two 120 " 2“中国二120”
3 " Switzerland One 45 " 3“瑞士一号45”
4 " China One 90 " 4“中国一号90”
5 " UK Two 50 " 5“UK Two 50”
This is how I get the array using xpath: 这是我使用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
What I would like to do with this array is to sort out and return only the matches. 我想对这个数组做的是整理并仅返回匹配。 Eg I would like for it to return only UK and China, so the array would look like this.
例如,我希望它只返回英国和中国,所以数组看起来像这样。
0 " UK One 150 " 0“UK One 150”
1 " China Two 120 " 1“中国二120”
2 " China One 90 " 2“中国一号90”
3 " UK Two 50 " 3“英国两个50”
You can do it like this with help of sort()
filter()
and regex
你可以借助
sort()
filter()
和regex
What i did is first filter all the elements which contains either UK
or China
. 我所做的是首先过滤包含
UK
或China
所有元素。
Now on this filtered array i need to capture the number using regex and sorted them in descending order. 现在在这个已过滤的数组上,我需要使用正则表达式捕获数字并按降序对它们进行排序。
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);
You can filter your array using the regular expression and then sort the result on the numeric value. 您可以使用正则表达式过滤数组,然后对数值进行排序。
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);
You can use a form of Schwartzian transform to "decorate" the data by extracting the name of the country, and the number using a array.map()
and regex. 您可以使用Schwartzian变换的形式通过提取国家/地区的名称以及使用
array.map()
和regex的数字来“装饰”数据。
Now you can filter by the country, sort by the number, and extract the str using another map. 现在,您可以按国家/地区进行过滤,按数字排序,然后使用其他地图提取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.