Skip to content
Advertisement

Replace an item in an array that doesn’t match any item in another array with a specific value

I’m still VERY new to Javascript and I’m having trouble with looping through an array and replacing items. I hope this explanation is clear.

I have an array that looks like this:

[
  '1:1',   'blah',
  '1:2',   undefined,
  '1:3',   'smith',
  '1:4',   'blah',
  '1:5',   'williams',
  '1:6',   'blah',
  '1:7',   'blah'
]

and I have another array that looks like this:

[ 
   'taylor', 
   'smith', 
   'williams', 
   'brown'
]

I want to replace any value in the first Array that isn’t in a /([0-9]+):([0-9]+)/g format and isn’t found in the second array. So all the “blah” and “undefined” in the first Array should be replaced with johnson but the names that match the second Array and the #:# numbers still remain, so the output shows:

[
  '1:1',   'johnson',
  '1:2',   'johnson',
  '1:3',   'smith',
  '1:4',   'johnson',
  '1:5',   'williams',
  '1:6',   'johnson',
  '1:7',   'johnson',
]

Advertisement

Answer

We can use a simple if statement inside a for loop to achieve what you are looking for.

var originalArray = [
  '1:1',   'blah',
  '1:2',   undefined,
  '1:3',   'smith',
  '1:4',   'blah',
  '1:5',   'williams',
  '1:6',   'blah',
  '1:7',   'blah'
];

var matchArray = [ 
   'taylor', 
   'smith', 
   'williams', 
   'brown'
];

for (var i = 0; i < originalArray.length; i++) {
    var value = originalArray[i];
    //Check if it matches your RegEx
    if (value !== undefined) {
      var doesItMatchRegEx = value.match(/([0-9]+):([0-9]+)/g);
    } else {
      originalArray[i] = "johnson";
    }
    //Check if it is in your second array
    var isItInSecondArray = matchArray.includes(value);
    if (!doesItMatchRegEx && !isItInSecondArray) {
        //Let's replace it with Johnson
        originalArray[i] = "johnson";
    }
}

console.log(originalArray);    
Advertisement