Performing a search through a string array and updating a specific portion of each string

I am faced with an array containing a long list of Strings, and my goal is to filter out all the strings that begin with 'INSERT ALL' and replace the number inside the parentheses with the string ' NULL'

Here is the original array:

let arrSt = [ 'INSERT ALL bmw model 320d (111, bmw)', 'ford focus st d (222, ford)', 'INSERT ALL audi a5 rs (333, audi)', 'opel astra d (444, opel)', ]

This is the desired modified array:

[ 'INSERT ALL bmw model 320d (NULL, bmw)', 'ford focus st d (222, ford)', 'INSERT ALL audi a5 rs (NULL, audi)', 'opel astra d (444, opel)', ]

This is the approach I took:

arrSt.filter((items: any) => items.startsWith('INSERT ALL')) .map((item: any) => item.replace(/\(\d+,/g, '(NULL,'))

However, despite using the .map method, the modifications do not seem to persist when checking the result using console.log(arrSt). Why does this method not affect the array as intended?

UPDATE:

In order to modify elements in an array of strings based on specific criteria, such as identifying those starting with a particular prefix like 'INSERT ALL', I need to implement a solution that caters to such requirements.

For example, given the array ['bmw', 'ferrari'], I should only modify strings that start with 'INSERT ALL bmw' or 'INSERT ALL ferrari'. This ensures that only relevant records are updated while leaving out others that do not meet the specified conditions.

Answer №1

If you want to keep all elements in an array, even those that remain the same, instead of using Array#filter, consider using Array#map and a conditional check like this:

const 
      arrSt = [ 'INSERT ALL bmw model 320d (111, bmw)', 'ford focus st d (222, ford)', 'INSERT ALL audi a5 rs (333, audi)', 'opel astra d (444, opel)' ],
      
      newArr = arrSt.map(
        item =>
          item.startsWith('INSERT ALL') ?      //check if the item starts with 'INSERT ALL'
          item.replace(/\(\d+,/g, '(NULL,') :  //change it if it does
          item                                 //leave it unchanged if it does not
      );
      
console.log( newArr );

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

Component failing to refresh with each key modification

My understanding is that adding a key attribute to a component should make it reactive when the key changes. However, with a v-navigation-drawer from Vuetify, this doesn't seem to have any impact. I've tried making arbitrary changes to the logge ...

Combine going to an anchor, performing an AJAX request, and opening a jQuery-UI accordion tab all within a

My goal is to have the user click on the hyperlink below, which will (1) anchor to #suggestions, (2) navigate to the url suggestions.php?appid=70&commentid=25961, and (3) open the jquery-ui accordion #suggestions. However, I am facing an issue where c ...

What is preventing React CLI from installing the template as TypeScript?

When I run npm init react-app new-app --template typescript, it only generates a Javascript template project instead of a Typescript one. How can I create a Typescript project using the CLI? Current Node JS version: 15.9.0 NPM version: 7.0.15 ...

Using Jquery to automatically populate an input field if the user already exists

I'm currently working on populating a form if the user input for name and firstname already exists in my database. However, I am facing an issue with my JavaScript program where it fails to check if the name and firstname combination already exists i ...

Unable to retrieve data from MySQL Database using Express Route

Struggling to understand how to execute a MySQL database query within the promise in my route file. Currently, I am developing a RESTful API for interacting with a MySQL database using GET methods. The technologies being utilized are Express for the backen ...

What is the best method to set one div as active by default in jQuery UI Accordion?

$(window).load(function(){ $.fn.togglepanels = function(){ return this.each(function(){ $(this).addClass("ui-accordion ui-accordion-icons ui-widget ui-helper-reset") .find("h3") .addClass("ui-accordion-header ui-helper-reset ...

PageCallbacks in .NET 1.1

Is it possible to utilize PageMethods in .NET 1.1 for making server-side method calls from the client side? Could you provide a brief explanation on how to use this feature by calling PageMethods.MyMethod(); ? ...

What are the steps to create a responsive Coin Slider?

Once the slider is generated, it appears that there is no built-in method to resize it, causing issues with responsive design. Is there a way to adjust the size of the Coin Slider plugin based on the media queries in Twitter Bootstrap 3? Take a look at C ...

Poorly formatted mui table representation

I have utilized the Table component from @mui/material and referenced the documentation at https://mui.com/material-ui/react-table/. To reproduce the issue, I have created a static table with fixed values. Here is the code snippet: <TableCo ...

Adding an onload event in a function-based component without using a fetch call

Looking at the code snippet below for a React component: import React from "react"; import { Carousel } from "react-bootstrap"; function CarouselHome() { return ( <> ...

iPad problem resolved: Disable click hover and double-click issue

I'm experiencing a problem with my web application specifically on Safari for iPad. I have to click twice in order to actually perform the click on the <a> tag. The first click triggers a hover effect, similar to when you hover with a mouse on d ...

Implementing the session injection into a request body within an asynchronous function in Node.js

I've been trying to inject a session value into the request in order to use it in various parts of my app. What I'm currently attempting is to call a function by providing an ID to search for a user in the database and retrieve the name of that s ...

Ways to display additional selected values in a select menu

I have a basic form on my website that includes options like: Select 1 and Select 2. I would like to set it up so that if I select value Home in Select 1, the value in Select 2 changes to something like residence. How can I achieve this using a database? ...

I require adding a new line of information into the database table

I am looking for help with adding data into a table without any user inputs. Specifically, I want to add data by passing them into an array and then be able to call them at the "Add Site" button so that the row is added into the table. Can someone assist m ...

Limit the selection of 'pickable' attributes following selections in the picking function (TypeScript)

In the codebase I'm working on, I recently added a useful util function: const pick = <T extends object, P extends keyof T, R = Pick<T,P>>( obj: T, keys: P[] ): R => { if (!obj) return {} as R return keys.reduce((acc, key) => { re ...

Issue with IE11: the selected list is not displayed when using the <s:optiontransferselect> tag

When moving groups from left to right in the s:optiontransferselect for selectedGrps and unselectedGrps, the SelectedGroups list is showing as null on form submission in IE11. However, in Chrome and Mozilla, it functions correctly. Any advice would be grea ...

json array: Tips for adding elements to a new array

In order to achieve my goal, I am looking to create a JSON array structure similar to the one shown below: var args = [{ name: 'test', value: 1 }, { key: 'test2', value: 2}]; How can I modify the code snippet provided below to generat ...

How to retrieve values from checkboxes generated dynamically in php using jquery

This is a unique question and not related to event binding or any suggested duplicates. Hello, I am facing an issue while trying to fetch the value of a checkbox to send it in an ajax request to a PHP page. The checkboxes are dynamically created using PHP ...

Modifying Copyright Feature in Footer

I am attempting to implement this function within my dark-colored footer: import Typography from '@material-ui/core/Typography'; function Copyright() { return ( <Typography variant="body2" color="textSecondary" align="center"> ...

"Initiate an Ajax call in Full Calendar before an event is displayed on the calendar

I need guidance on how to integrate ajax calls with the Full Calendar documentation. Specifically, I want to make an ajax call to a WordPress database before each event is rendered on the calendar. The response from the call will determine the color of the ...