Obtain purified strings from an array of elements

In my collection of objects, there is a specific string mentioned:

[
  {
    "id": 2240,
    "relatedId": "1000"
  },
  {
    "id": 1517,
    "relatedId": "100200"
  },
  {
    "id": 1517,
    "relatedId": "{{100200}}"
  },
  {
    "id": 2236,
    "relatedId": "{{271}}+{{269}}+{{267}}"
  }
]

My objective is to extract the related ID keys that contain "{{" or "}}" in them. Then, I intend to remove any non-numeric characters and provide an array of these numbers. The resulting array should be:

[100200,271,269,267]

This code achieves the desired result:

const objArray = [
  {
    "id": 2240,
    "relatedId": "1000"
  },
  {
    "id": 1517,
    "relatedId": "100200"
  },
  {
    "id": 1517,
    "relatedId": "{{100200}}"
  },
  {
    "id": 2236,
    "relatedId": "{{271}}+{{269}}+{{267}}"
  }
];

const numArray = objArray.map(v => v.relatedId).filter(el => el.includes('{{'))
      .map(v => v.replace(/[{{}}]/g,'').split('+')).flat()
      .map(Number);
      
console.log(numArray)

Is there a more elegant way to accomplish this task? It seems like there should be a simpler solution.

Answer №1

One approach is to concatenate the strings before using a global regular expression to extract values enclosed in brackets.

const objArray=[{id:2240,relatedId:"1000"},{id:1517,relatedId:"100200"},{id:1517,relatedId:"{{100200}}"},{id:2236,relatedId:"{{271}}+{{269}}+{{267}"}];

const numArray = objArray
    .map(v => v.relatedId)
    .join('')
    .match(/(?<={{)\d+/g)
    .map(Number);
      
console.log(numArray)

If there is a possibility of no match at all, .match will return null - in that case, to prevent errors, make the following adjustment:

const objArray=[{id:2240,relatedId:"1000"},{id:1517,relatedId:"100200"},{id:1517,relatedId:"{{100200}}"},{id:2236,relatedId:"{{271}}+{{269}}+{{267}"}];

const numArray = (
    objArray
        .map(v => v.relatedId)
        .join('')
        .match(/(?<={{)\d+/g)
    || []
)
    .map(Number);
      
console.log(numArray)

Answer №2

Here's how I approach it:

objArray.extractIds().convertToNumbers()

** Please keep in mind:
This method utilizes a custom extraction function and number conversion technique.

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

Error found in Paper.js at line 81: Uncaught TypeError - Unable to access properties of undefined (specifically '1') while utilizing Material UI and Joy UI

I am encountering an issue while using react js with material UI and JoyUI, where I am getting a blank screen. Below is the code snippet causing the problem: import React from 'react'; import { CssVarsProvider } from '@mui/joy/styles'; ...

Adjust the color of the entire modal

I'm working with a react native modal and encountering an issue where the backgroundColor I apply is only showing at the top of the modal. How can I ensure that the color fills the entire modal view? Any suggestions on how to fix this problem and mak ...

Implementing CodeIgniter's HMVC structure to dynamically update data using AJAX functionality

Recently, I came across an AJAX function in an open-source code that caught my attention. function edit_person(id) { save_method = 'update'; $('#form')[0].reset(); // reset form on modals //Ajax Load data from ajax $.ajax({ ...

Getting a ReferenceError while trying to use a MongoDB Collection variable in an external resolver file that had been imported through mergeResolvers

Here is a simplified example to illustrate the issue at hand. When using the resolver Query getAllUsers, the MongoDB Collection Users is not accessible in the external resolver file user.js. This results in the following error when executing the query: ...

Issue: Infinite loops detected in AJAX functions

I am using $.get methods in the following code snippet: $.get("/url" , function(z) { var a = $(z).find("span"); for (var i = 0 ; i<a.length; i++){ var v = $(a).eq(i).children("strong:first").text(); alert(v); } }); However, the s ...

Maintain the values of radio buttons, dropdowns, and checkboxes using Javascript

When I click on a radio button, it activates a drop down menu. Upon selecting different values from the drop down, various checkboxes become visible. Now, I want to preserve the selection of the radio button along with the selected drop down values and ch ...

Transform markdown into HTML code

Is there a way to effectively transform a string that resembles the following format: '* [-]Tree Item1', '** [-]Tree Item1-1', '*** Tree Item1-1-1', '*** Tree Item1-1-2', '*** Tree Item1-1-3', '** Tre ...

Utilize Javascript to load content dynamically while ensuring each page has a distinct link to individual content pages

As a newcomer to web development, I wanted to share my issue in hopes of finding a more efficient solution than what I've been attempting. Recently, I made changes to my website so that content is loaded dynamically using the jQuery load() function. T ...

What is the best way to save a webpage when a user clicks a button before leaving the page with Javascript

I've exhausted all my options in trying to find a way to trigger a button that saves the page upon exit, but it never seems to work. I need the event to occur even if the button is not visible at the time of the page exit. The new security protocols o ...

Retrieve an item from an array based on the unique ID value of the button that was clicked using

I am working with a phones array that is populated with JSON data: var phones = [ { "age": 0, "id": "motorola-xoom-with-wi-fi", "imageUrl": "img/phones/motorola-xoom-w ...

What is the best way to highlight selected navigation links?

Recently, I implemented a fixed navigation bar with relevant links on a website. The navbar includes a jquery script for smooth scrolling when clicked. However, I am struggling to add a selected class to the clicked link. Despite trying various solutions f ...

Where should Babel and Webpack be placed in your package.json file - under devDependencies or Dependencies?

I'm a beginner when it comes to npm and I have doubts on what should be included in dependencies as opposed to devDependencies. I understand that testing libraries belong in dev, but what about tools like babel and webpack? Should they also be categor ...

exchange information among distinct domains

Two distinct services are operating on separate machines, resulting in different URLs for each service. The user initially accesses the front end of the first service. Upon clicking a button on this service, the user is directed to another front end servi ...

Tips for revealing a hidden HTML tag

I am currently trying to validate the content within #textd to ensure it is not empty and contains more than 150 characters. If it meets these conditions, I need to transfer the content to another webpage; otherwise, display an error message based on the c ...

Leverage Redis to facilitate memory sharing among node.js instances in RxJS

We are currently developing a project that involves creating an event processor using RxJS. The system relies on specific rules where input is collected from various sources and output is generated based on the frequency of inputs exceeding a certain thres ...

When utilizing the header slot in v-data-table, an empty header row is unexpectedly appearing

Having an issue with adding an extra empty row when using the header slot in v-data-table from Vuetify2. Check out the codepen here: https://codepen.io/satishvarada/pen/rNBjMjE?editors=1010 Vue.component('pivot-table',{ data:()=>({ ...

Can a javascript variable be accessed after loading an iframe and returning to the page?

Using a jquery plugin known as colorbox, my colorbox simply opens an iframe on the screen. This detail may not be relevant, as the core issue at hand is that I have 3 variables on my parent window that are retrieved from an AJAX call using jquery: data.re ...

Trouble with the 'uppercase' package in Node.js: Receiving ERR_REQUIRE_ESM error while utilizing the require() function

I am encountering a problem with the 'upper-case' module while developing my Node.js application. My intention is to utilize the upper-case module to convert a string to uppercase, but I'm running into difficulties involving ESM and require( ...

Why is the type of parameter 1 not an 'HTMLFormElement', causing the failure to construct 'FormData'?

When I try to execute the code, I encounter a JavaScript error. My objective is to store the data from the form. Error Message TypeError: Failed to create 'FormData': argument 1 is not an instance of 'HTMLFormElement'. The issue arise ...

What could be causing the client to not receive the socket.io broadcast in the designated rooms?

My client isn't receiving the broadcast sent to the room. I have tried replacing socket.to(roomName).emit('join', currentUser); with socket.emit('join', currentUser); and it works, but I prefer using rooms in this scenario. Any ass ...