Query for looping through JavaScript: what is the technique for extracting only number elements to create a fresh array?

I have a set of tasks that need to be automated in my daily workflow. The specific task requires:

  1. Receiving messages in my IM, and appending the first, second & third number from each link with a "|" delimiter.
  2. If there are only 2 numbers in the sequence, a 0 should be added at the beginning.

For example, for the cleanResult scenario, the desired outcome is:

finalResult = ["https://www.example.com/firstlink|500",
"https://www.example.com/firstlink|150",
"https://www.example.com/firstlink|30",
"https://www.exmaple.com/secondlink|600",
"https://www.exmaple.com/secondlink|150",
"https://www.exmaple.com/secondlink|30",
"https://www.example.com/thirdlink|500",
"https://www.example.com/thirdlink|150",
"https://www.example.com/thirdlink|30",
"https://www.example.com/forthlink|600",
"https://www.example.com/forthlink|100",
"https://www.example.com/forthlink|20",
"https://www.example.com/fithlink|0",
"https://www.example.com/fithlink|200",
"https://www.example.com/fithlink|50"
]

Progress so far:

const urlRegex = /(https?\:\/\/)?([^\.\s]+)?[^\.\s]+\.[^\s]+/gi;
const digitRegex = /^(?=.*\d)[\d ]+$/;

cleanResult = ["https://www.example.com/firstlink",
"https://www.exmaple.com/secondlink",
"https://www.example.com/thirdlink",
"500    150    30",
"https://www.example.com/forthlink",
"600    100     20",
"https://www.example.com/fithlink",
"200   50"
]

cleanResult.forEach((item, index) => {
       if (item.match(digitRegex)) {
              //Code implementation pending...
      }
})

Answer №1

Are elements within the cleanResult array always either a URL or a number? If so, we can easily determine this by checking the first character of each string. If the first character is not a number (indicating a non-URL), then we know it must be a numerical value. We can then manipulate the URL which should be the previous element in the array:

// Placeholder to store current URL
let currentURL = ''

// Iterate through each element in cleanResult
cleanResult.forEach((item, index) => {
  // Get the first character of the current item
  const first = item[0]

  if (!Number.isInteger(first)) {
    // Store as URL if the first character is not a number
    currentURL = item

  } else {
    // Handle numerical values
    const numbers = item.split('\t') // Split by tab delimiter
    numbers.forEach((n) {
      // Create new URL pattern combining currentURL and number
      const newURL = currentURL + '|' + n

      // Add new URL to finalResult array
      finalResult.push(newURL)
    })
  }
})

This approach breaks down the task into smaller steps for easier understanding, without using regex. It assumes input will be either a URL or a list of tab-separated numbers. While there may be more efficient ways to achieve this with fewer lines of code, taking a verbose approach can help grasp fundamental concepts especially for those learning programming.

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

Is there a way to transfer an image from background.js to background.html?

I'm in the process of creating a chrome extension that involves making an API call every hour to retrieve an image, which I then want to save in chrome.storage.local. However, the size of the image is quite large, so I'm resizing it using a canv ...

leveraging hooks in NextJS app router for static page generation

How can I make an action take effect on page-load for the app router equivalent of statically generated pages from static paths in NextJS? Everything is working fine with my page generation: // app/layout.js import Providers from '@/app/Providers&apo ...

Expanding the flexbox container to accommodate additional divs when they are added

I'm encountering an issue with a div not extending properly, causing two other divs to overlap. I've managed to position the divs correctly, but now I need the "100% all beef weenies" text to appear below the items. Any suggestions on how to achi ...

How can I remove the script file from my req.params?

Can anyone help me figure out how to extract the :rid from my req.params without getting two values, one being the rid and the other the script file? Take a look at this screenshot from the console.log: console.log picture This is my route code: router. ...

Vue.js - Exploring methods to append an array to the existing data

I am looking to structure my data in the following way: Category 1 Company 1 Company 2 Company 3 Category 2 Company 1 Company 2 Company 3 Below is my code snippet: getlist() { var list = this.lists; var category this.$htt ...

Controller Not Deserializing Ajax File Upload in MVC 5

There seems to be an issue with deserializing the data sent using the multipart/form-data type within an MVC 5 project. Despite appearing valid in Fiddler, the data is not being mapped into the controller method. While debugging, it is evident that all par ...

Using jQuery to import certain library causes the XPage to completely lock up

My XPage only relies on 2 js imports - one being JQuery and the other dependent on JQuery specifically for smart companies search in the Russian Federation. However, a challenge arises when trying to import the second library as it causes the entire page t ...

Extract the body.req object within a loop in a Node.js application

I'm looking to efficiently parse and save the body of a POST request using Mongoose in Node.js. Is there a way to use a for loop to accomplish this task, rather than manually saving every property? My ideal solution would involve something like: for ...

Creating a pair of linked dropdown menus in ReactJS that open simultaneously

Having two dropdown menus can be a bit cumbersome, especially when you have functions dedicated to opening each one individually. It would be more efficient to combine them into one function for simplicity. If anyone has a solution for this, I would greatl ...

Exploring the world of reactive programming in JavaScript by transforming traditional AJAX calls into Bacon.js streams while incorporating

How can I develop a method to convert calls to the server API to a Bacon.js / RxJs stream while supporting pagination? With pagination, I aim to keep track of the last requested item index and retrieve the next set of items based on the page size to popul ...

Updating the value of a key within a jQuery object

A custom modal plugin has been developed with options that can be set by default or by the user. These values are passed to a function for updating, and it is desired that the options object as a whole is updated rather than individual values. The user&ap ...

Tips on assigning a value to a dynamically generated drop-down element

I used arrays of strings to populate drop-down menus. Is there a way to automatically set the value of each option to match the text content? el.value = opt; seems to be ineffective. var validCoursesKeys = ['opt 1','opt 2','opt ...

EJS: display length when this condition is met

Imagine a scenario where there is a MySQL database connected to NodeJS and EJS. The database contains three categories: OK, WARNING, and FALSE. How can the total count of each category be obtained from the database? An attempt was made by implementing th ...

How to effectively delete the class from a navigation list item

Looking for some inspiration? Check out the basic visuals for this question here. But let me break it down for you. This snippet shows the HTML & CSS behind a tabbed-carousel, with a condensed version for clarity: <style> #myCarousel-100 . ...

Leverage the power of the select function in Angular to transmit multiple parameters

In Angular Js, is there a way to utilize a select element in a manner similar to how you can use a list of links? For instance, if I have links set up like this: <a ng-click="ctrl.change('argument1','argument2')">One</a> & ...

jQuery - easily adjust wrapping and unwrapping elements for responsive design. Perfect for quickly undo

Within the WordPress PHP permalinks and Fancybox plugin, there are elements enclosed in an "a" tag like so: <a href="<?php the_permalink(); ?>" class="example" id="exampleid" data-fancybox-type="iframe"> <div class="exampledivclass"> ...

Using Star ratings in amp CSS with Django template Tag: A complete guide

I need to implement a star rating display on amp pages based on values retrieved from the database using django template tags. How can I achieve this considering the ratings are in float format? Additionally, is it possible to apply the same code to non-am ...

When the function is called, it will return the global `this

Attempting to bind the user object as 'this' and default time as the first parameter utilizing the function.call method let user = { name:'rifat', txt (time, msg){ console.log('['+time+ '] '+ this.name+ &apo ...

My strategies for addressing caching problems in my ReactJS site

Currently tackling ReactJS projects on a website with the URL . Things seem to be running smoothly, until my SEO-savvy friend pointed out an issue with caches. He advised me to visit this cache URL: , where Google should display the main page but instead s ...

Looking for a way to assign the (file path to kml) to a variable in your code while utilizing geoxml3?

Is there a way to store the KML file in a variable before parsing it with myParser? Check out this link for more information: https://github.com/geocodezip/geoxml3 var myParser = new geoXML3.parser({map: map}); myParser.parse('/path/to/data.kml' ...