Home > Blockchain >  Filter an array of string and replace a part of the string
Filter an array of string and replace a part of the string

Time:01-17

I have an array with a list of Strings (it's quite long, this is just an example), what I'm trying to do is filter all the strings that start with 'INSERT ALL' and modify the number inside the parentheses by the string ' NULL'

This 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 array I'm trying to get:

[ '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 what I do:

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

When displaying the result in the console, console.log(arrSt) returns the original array, nothing has been modified, I've been using .map for a short time, but why doesn't it affect the array?

UPDATE:

From an array of string identify the elements that begin with that string. That is to say:

This is the array: ['bmw', 'ferrari']

I need to modify all the elements that start with INSERT ALL bmw and INSERT ALL ferrari.

In this case, only the first record would be updated, since the second begins with INSERT ALL audi

CodePudding user response:

To retain all items, including those that do not change, you may not need to use Array#filter but Array#map and if as below:

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

  • Related