I have an array that contains several countries followed by an option and a number.
0 " UK One 150 "
1 " Switzerland Two 70 "
2 " China Two 120 "
3 " Switzerland One 45 "
4 " China One 90 "
5 " UK Two 50 "
This is how I get the array using 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. E.g. I would like for it to return only UK and China, so the array would look like this.
0 " UK One 150 "
1 " China Two 120 "
2 " China One 90 "
3 " UK Two 50 "
You can do it like this with help of sort()
filter()
and regex
What i did is first filter all the elements which contains either UK
or 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);