Filter an array using regular expressions in JavaScript

Currently, I am facing a challenge in creating a new array of strings by filtering another array for a specific pattern.

For example:

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

I believe this pattern can be found in the given string as well. However, my initial approach was to split the string at each / :

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

Essentially, I need to create two different arrays that are filtered based on the starting pattern of these strings. OG and NW are fixed prefixes that won't change, but I am unsure about the numbers that follow. The backend sends this data as OG(original ticket) and NW(new ticket), so these prefixes are constant. I need to identify strings starting with these prefixes and place them in their respective arrays:

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

Answer №1

To achieve separate arrays, you can utilize the filter method along with startsWith

let originalData = "4162416245/OG74656489/OG465477378/NW4124124124/NW41246654";
let splitArray = originalData.split('/');

const ogArray = splitArray.filter(item => item.startsWith("OG"));
const nwArray = splitArray.filter(item => item.startsWith("NW"));
console.log(ogArray);
console.log(nwArray);

Another approach is to use reduce to iterate through the collection once and store the data in an object with separate properties.

let originalData = "4162416245/OG74656489/OG465477378/NW4124124124/NW41246654";
let splitArray = originalData.split('/');

const result = splitArray.reduce((accum, current) => {
  if (current.startsWith("OG")) accum.og.push(current)
  if (current.startsWith("NW")) accum.nw.push(current)
  return accum;
}, {
  "nw": [],
  "og": []
})

console.log(result);

Answer №2

You have the option to utilize the Array.prototype.reduce() method in JavaScript to accumulate the elements into an object that includes all tickets.

As a result, you would get:

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

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

const ticketsList = initialString.split('/').reduce((accumulator, current) => {
    if(current.startsWith('OG')) accumulator["OG"].push(current)
    else if(current.startsWith('NW')) accumulator["NW"].push(current)

    return accumulator
  }, {OG: [], NW: []})
  
console.log(ticketsList)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The type is lacking the following properties in array.push

Encountering an issue with the register page in my IONIC app. Currently, I am utilizing a data.json file to store all user data, and I aim to create a new member with minimal information required (name, email, password) while leaving other fields empty fo ...

Compatibility issues between jQuery and AngularJS are causing problems

Currently, I am facing a compatibility issue between RequireJS and Angular in my setup. Everything functions without any problems when using jQuery version 1.7.2. However, I wanted to upgrade to jQuery 1.8.1 along with jQuery UI, but unfortunately, my Angu ...

Having trouble setting the image source in HTML with Node.js

I am a beginner with nodeJS and I am having trouble setting the src attribute of an img tag in my client side html. My node server is running on port 3000 and everything works fine when I visit http://localhost:3000. Here is the code from my server.js fil ...

Creating a character jump animation on an HTML5 canvas

While following a tutorial on creating character animations, I encountered an issue. The tutorial, located at , made it easy to make the character move left (the right movement was already implemented). However, I am struggling with how to animate the char ...

Deciphering JSON data in a textarea following a POST request

I am struggling with decoding a JSON string in PHP and I have identified the problem causing it. However, I am unsure of how to fix it. My approach involves putting an array that I convert to JSON into a hidden textarea, which I then post along with other ...

Steps for automatically adding a new user to the AddThis service for configuring analytics services

As I work on creating a Backoffice for my website, I am looking to provide a mobile version for all users uniformly. To enhance user experience, I plan to introduce a "Report" tab in the back office interface. This tab will display analytics information g ...

Adding the location of the onClick event to the hook - a step-by-step guide

Here is the code I am working with: import { MapContainer, TileLayer } from "react-leaflet"; import React, { useState } from 'react'; export default function App() { const [positionLat, setPositionLat] = useState(null); ...

In what way can a container impact the appearance of a child placed in the default slots?

Visiting the vue playground. The main goal is for the container component to have control over an unspecified number of child components in the default slot. In order to achieve this, it's assumed that each child component must either hold a propert ...

Retrieving JSON information from a nested array

I've noticed that this question has been asked frequently, but I haven't come across a case similar to mine. Here's the array printed out from a JSON response: Array ( [contents] => { "type": "XXXXXXXXXXXXXXX", "previous": " ...

What is the best method for swapping strings within two separate multidimensional arrays?

I am attempting to replace strings from two separate multidimensional arrays by utilizing str_replace and categorized arrays. I experimented with using array_walk_recursive twice: once externally and once internally, as shown below: $array1 = [ &apos ...

npm's protocol for handling callback errors

While exploring the coding style guidelines by npm, I stumbled upon a rather enigmatic suggestion: Be very careful never to ever ever throw anything. It’s worse than useless. Just send the error message back as the first argument to the callback. Thi ...

Comparing org.json.simple with org.json: Unearthing the Distinctions

JSONArray js1 = new JSONArray(); for (Product product : plist) { JSONObject jo1 = new JSONObject(); jo1.put("image", product.getProductImages()); jo1.put("name", product.getName()); jo1.put("price", product.getPrice()); js1.add(jo1); } ...

Launching an embedded webpage in a separate tab within the main browser window

In my current setup, I have implemented an iframe within the main window. The iframe includes a form where users can input data and submit it. Currently, I achieve the submission with the following code: var openURL = '/results/finalpage'; windo ...

The AudioContext feature is functioning properly on Google Chrome but experiencing issues on Safari

In Safari, I understand that audio context needs to be created after user interaction. Despite this knowledge, the code below still didn't produce the desired result. HTML <button onclick="play">Play</button> Javascript functio ...

AngularJS controller containing a nested app

Is there a way to implement this structure using AnglularJS? <body ng-app="mainBodyAppWrapper"> <div ng-controller = "mainBodyController"> <div ng-app="myApp"> <div ng-controller="controller3"> ...

When passing context to createPage for use in a query, there may be issues if a string is inadvertently converted to a number, causing the query to fail

I am facing an issue with a page creation function that I have implemented. Here is the code snippet: createPage({ context: { productId: String(productId) }, Despite explicitly converting the ID to a string, the page template is still receiving it as a ...

How can I attach an existing event to a dynamically loaded element using AJAX?

In the main page of my website, there is a button: <button class="test">test</button> Additionally, I have included the following script in my code: $('.test').on('click',function(){ alert("YOU CLICKED ME"); } ...

Step-by-step guide on developing an AngularJs provider using TypeScript

As I've developed a Directive that incorporates various Css classes, it would greatly enhance its flexibility if the Css classes could be configured at Application start within the config section. I believe utilizing a provider is the appropriate appr ...

Is there a way for mocha to conduct a recursive search within my `src` directory in order to find a specific

In my npm project, I want to replicate the structure used by Meteor: there is a source file called client.js and its corresponding test file named client.tests.js residing in the src/ directory. The tests should be executed with the npm test command. I am ...

Using jQuery to remove the last two characters from a specified class

I have a simple task at hand. I am trying to use the slice method in JavaScript to remove the last two characters from a string that is generated dynamically within a shopping cart. Instead of displaying a product as $28.00, I want it to display as $28. S ...