Joe Berg
Joe Berg

Reputation: 381

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 "

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 "

Upvotes: 1

Views: 67

Answers (3)

Ori Drori
Ori Drori

Reputation: 191976

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.

Now you can filter by the country, sort by the number, and extract the str using another map.

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

Upvotes: 1

Hassan Imam
Hassan Imam

Reputation: 22534

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

Upvotes: 1

Code Maniac
Code Maniac

Reputation: 37755

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

Upvotes: 1

Related Questions