Swap out an element in a list that does not correspond to any element in a separate list with a designated value

I am fairly new to Javascript and currently struggling with looping through an array and replacing items. I hope my explanation is clear.

Here is the initial array:

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

and here is another array:

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

The goal is to replace any value in the first array that does not follow the format of /([0-9]+):([0-9]+)/g and is not found in the second array. Therefore, all occurrences of "blah" and "undefined" in the first array should be replaced with johnson. Any names that match the second array as well as the #:# numbers should remain unchanged. The desired output is:

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

Answer №1

To achieve the desired outcome, we can incorporate a straightforward if statement within a for loop.

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];
    //Verify if it conforms to your RegEx
    if (value !== undefined) {
      var doesItMatchRegEx = value.match(/([0-9]+):([0-9]+)/g);
    } else {
      originalArray[i] = "johnson";
    }
    //Check its presence in the second array
    var isItInSecondArray = matchArray.includes(value);
    if (!doesItMatchRegEx && !isItInSecondArray) {
        //Replace with Johnson if mismatched
        originalArray[i] = "johnson";
    }
}

console.log(originalArray);    

Answer №2

To simplify things, let's denote the primary array as arr, and the array of names as names. The following code snippet can help achieve the desired outcome:

  • arr.map(item => !/([0-9]+):([0-9]+)/g.test(item) && !names.includes(item) ? 'johnson' : item)

Answer №3

In my opinion, for the task at hand, utilizing the map() function of the array in a functional manner would be highly effective. Another option to consider could be using filter(), but since the goal is to replace specific entries, map() achieves it with greater efficiency.

With the Array.prototype.map() method, a specified function is executed on each element of the array, and the result of that function is stored at the corresponding index in the new array that is returned.

validNames = ['taylor'...];
numberFormatRegex = /([0-9]+):([0-9]+)/g;

// The following function will be applied to each item in the array; the output of the function becomes the new value in the mapped array
mapFunction = (value) => {
  if(!validNames.includes(value) && !numberFormatRegex.test(value)){
    // Only values NOT present in the validNames list AND failing the regex test will follow this condition
    
    return 'Johnson';
  }
  // This code block executes only if the previous return statement did not trigger, thus applying to valid values

}

// Invoke the map() method with our designated function and store the result in a new array
// It's important to note that the original inputArray remains unchanged, while the modified array is assigned to newArray
newArray = inputArray.map(mapFunction);


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 function Server.listeners is not recognized by the system

Currently, I am following a tutorial on websockets to understand how to incorporate Socket.IO into my Angular project. Despite meticulously adhering to the instructions provided, I encountered an error when attempting to run my websockets server project: ...

Locate the absent date within a php array

I have a PHP array that contains attendance details for certain dates: Array ( [0] => Array ( [EmployeeAttendance] => Array ( [attendance_id] => 1 [arrival_datetime] ...

Exploring two data points within a two-dimensional array

As I attempt to compare the row and column location of two elements to determine if they are adjacent, I find myself at a loss after an extensive search without success on similar questions in SO. My primary inquiry revolves around the syntax in one speci ...

Make sure to wait until the fetch function is finished before triggering another action

When I run console.log(this.detaliiMP), it currently returns an empty array. My goal is to wait for the getData() function to retrieve the data and populate the detaliiMP array before logging it to the console. Check out the demo here const app = Vue.c ...

Displaying a sub-menu for specific menu options to fetch content using routes in ReactJS

Currently, I am in the process of learning the React JavaScript library. My goal is to develop a basic web application that consists of a menu, submenu, and content sections. For this project, I am using react 15.0.2, react-router 2.4.0, babel 6.5.2, and w ...

Expressjs Error- ReferenceError: cors has not been defined in this context

While working on creating a backend using ExpressJs, I encountered an error when running the backend. app.use(cors()) ^ ReferenceError: cors is not defined at Object.<anonymous> (C:\Users\hp\Desktop\Entri\kanba\ ...

What is the process for integrating a custom script prior to building in a react application?

I am facing an issue with the Chart library that I am using and in order to resolve it, I need to execute a specific script. The script can be found at this link: https://github.com/plouc/nivo/blob/master/scripts/patch-react-spring.js. I have considered ad ...

cPanel is incompatible with node version 12.16.0

I am facing a dilemma regarding hosting my node API, which was built using node version 12.16.0, on cPanel. The available version for node in cPanel is 12.9.0 (Most recent). How should I proceed? Is the node version really a critical factor in this case? ...

How should you proceed when npm install cannot locate a specific dependency, even though you can easily download it manually?

Currently, I am faced with a dilemma while attempting to execute a JavaScript file that is accompanied by a package.json file. The issue arises during the npm install command in the folder as it fails to locate one of the dependencies. To address this pro ...

Every 5 seconds, a message of "true" is sent. If the request does not reach the server within 10 seconds, how can a function be triggered?

For every 5 second interval, the client transmits the value "true". How can a function be triggered on the Node.js server if no request is received within a 10-second timeframe? Please provide an illustrative code example. Client: let time = JSON.stringi ...

Can someone assist me with navigating through my SQL database?

Struggling with a script that searches multiple fields in the same table, I need it to return results even if one or three parameters are left blank. My attempts using PHP and MySql have been fruitless so far, which is why I am reaching out to the experts ...

Simple JavaScript timer with loop and pause

Having trouble with a countdown script and encountering multiple issues. The script does not run smoothly Difficult to make it repeat (closure) Struggling with delaying the start and repeat (closure) Seeking assistance in fixing this code which should i ...

Guide to executing two child processes sequentially in Node JS

I am working on two processes within a function: one generates a JSON file from an audio while the other normalizes the generated JSON file. However, I'm facing an issue where only one of the processes runs at a time - when the first one runs, the se ...

Switch button - reveal/conceal details

I am looking for assistance in toggling the visibility of information when clicking on an arrow icon. I have attempted to use JavaScript, but it was unsuccessful. My goal is to hide the information below by clicking on the downward-facing arrow image , an ...

Generate an HTML document from a website page

Having difficulty grasping this concept. I am completely lost on where to begin. It is imperative that I determine how my website can generate a file (whether it be HTML or Text format) and enable users to download it, similar to the functionality in Goo ...

Unable to access variables beyond the function scope results in an undefined value

I'm currently working with an npm package that shortens URLs but I'm struggling because there isn't much documentation available. The package takes the "this.src" URL and shortens it, but when I try to use the "url" element in HTML, it retur ...

How to use jQuery to highlight the parent element when clicking on a child element?

I'm struggling with some HTML code that looks like the following: <ul> <li class="curent"><a href="home.html">Home</a></li> <li> <a href="javascript:void(0)">Products</a> <ul ...

What is the best way to incorporate a 'category filter' in Angular2?

Unique Scenario In my Angular2 application, I have implemented code in a component's view parent.component.html that iterates through an array of items and generates a new component for each item: <div class="list-items"> <!-- The colored ...

Setting configuration files in Node.js with npm configuration

I have developed a SAAS application on the Angular/NodeJS/Postgres+MongoDB stack that can establish connections with customer databases, cloud warehouses, S3 buckets, and more to load relevant information. Once I receive connection details from the Angular ...

I am encountering an issue with Angular where the following error message is displayed: "src/app/app.component.html:18:20 - error TS2339: Property 'DepScreen' does not exist on type 'AppComponent'"

This code snippet is from my app.component.html file: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0" ...