Home > Back-end >  Javascript filter array with regex
Javascript filter array with regex

Time:08-17

I am struggling at the moment with making a new array of strings from another array that I have to filter for certain pattern.

Example:

let originalString = "4162416245/OG74656489/OG465477378/NW4124124124/NW41246654"

I guess this could be matched from this string as well. But my initial approach was to split this string at each / :

let splitArr = originalString.split('/');
// splitArr = ["4162416245", "OG74656489", "OG465477378", "NW4124124124", "NW41246654"]

Basically what I do have to achieve is to have 2 different array that is filtered down by pattern of the start of this strings. OG and NW is always fix won't change but numbers after I don't know.. Backend sends this data as OG(original ticket) NW(new ticket) so those prefixes are fix, I have to check for string starting with them and put them in they array:

ogArr = ["OG74656489", "OG465477378"]
nwArr = ["NW4124124124", "NW41246654"]

CodePudding user response:

If you want 2 separate arrays, you can use filter and startsWith

let originalString = "4162416245/OG74656489/OG465477378/NW4124124124/NW41246654";
let splitArr = originalString.split('/');

const ogArr = splitArr.filter(s => s.startsWith("OG"));
const nwArr = splitArr.filter(s => s.startsWith("NW"));
console.log(ogArr);
console.log(nwArr);

Another option could be using reduce to travel the collection once, and pass in an object with 2 properties where you can extract the data from.

let originalString = "4162416245/OG74656489/OG465477378/NW4124124124/NW41246654";
let splitArr = originalString.split('/');

const res = splitArr.reduce((acc, curr) => {
  if (curr.startsWith("OG")) acc.og.push(curr)
  if (curr.startsWith("NW")) acc.nw.push(curr)
  return acc;
}, {
  "nw": [],
  "og": []
})

console.log(res);

CodePudding user response:

You can also use the Array.prototype.reduce() method to add the elements into an object containing all tickets.

This would lead to this results :

{
  "OG": [
    "OG74656489",
    "OG465477378"
  ],
  "NW": [
    "NW4124124124",
    "NW41246654"
  ]
}

let originalString = "4162416245/OG74656489/OG465477378/NW4124124124/NW41246654"

const tickets = originalString.split('/').reduce((acc, curr) => {
    if(curr.startsWith('OG')) acc["OG"].push(curr)
    else if(curr.startsWith('NW')) acc["NW"].push(curr)

    return acc
  }, {OG: [], NW: []})
  
console.log(tickets)

  • Related