Organize pairs of strings into a nested array within an array using Angular

Currently, I am working on a project in Angular. In this project, I have a string that contains special characters which I have successfully removed using regular expressions. Now, my goal is to arrange the first two strings within square brackets and the next two strings in another set of square brackets so they resemble coordinates. The desired output should look like the example below. Can someone please assist me with achieving this functionality?

test: any = "((-1.23568 75.87956), (-1.75682 22.87694))"

This is a snippet of my TypeScript code:


hello()
{
    this.new = ( this.test.replace(/[^\d. -]/g, ''));
    this.newarr = this.new.split(" ");    
    const result =  this.newarr.filter(e =>  e);
}

The current output stored in the result array looks like this:

["-1.23568", "75.87956", "-1.75682", "22.87694"]

However, the desired final output should be:

[ ["-1.23568", "75.87956"], ["-1.75682", "22.87694"] ]

Answer №1

One method you could try is using String.match() to extract the groups of coordinates, then applying Array.map() along with String.split() to split them into pairs.

let test = "((-1.23568 75.87956), (-1.75682 22.87694))";
const result = test.match(/[\d.-]+\s[\d.-]+/g).map(s => s.split(/\s/));
console.log('Result:', result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Answer №2

If you're looking to divide your initial array into portions, one option is to use the Array.prototype.splice() method.

pairs.push(initialArr.splice(0, 2))

You can then iterate through your initial array by dividing its length by two:

See a working demo here

Alternatively, consider updating your logic to extract pairs from your data instead of individual numbers, such as '

'-1.23568 75.87956,-1.75682 22.87694'
'. You can achieve this by splitting the string twice:

split(',') --> ['-1.23568 75.87956', '-1.75682 22.87694']

Then continue by splitting each pair using the space character:

split(' ')

Answer №3

One way to simplify complex regex logic is by utilizing the following approach:

const [a1, a2, b1, b2] = ["-1.23568", "75.87956", "-1.75682", "22.87694"]

const result = [[a1, a2], [b1, b2]]

If dealing with more than two pairs, you can do the following:

const array = ["-1.23568", "75.87956", "-1.75682", "22.87694", "-1.33343", "3.34432"]

const result = [];
for(let i = 0; i < array.length; i+=2) {
  result.push(array.slice(i, i+2))
}

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

Execute asynchronous code in a Next.js component without relying on the UseEffect hook

Within my nextjs application, there is a StrapiImage component that takes in an image object from the strapi backend api as a prop. This component sets the width, height, URL, and any additional props for the image. Essentially, it serves as a shortcut for ...

Error in TypeScript due to object being undefined

Exploring TypeScript and facing a challenge with setting properties in an Angular component. When I attempt to define properties on an object, I encounter an error message: ERROR TypeError: Cannot set property 'ooyalaId' of undefined Here is ho ...

Why does the CLI crash when attempting to retrieve all data from an Oracle Database with JQuery?

Trying to utilize JavaScript and Jquery for database search, a generic query.php file has been set up to pass in the database and query, returning an array. Strangely, when attempting to select all using *, the PHP server crashes with: https://i.stack.img ...

From an array to a collection of arrays

After collecting values from a table, I now have an array: arr = ["One", "0", "31.948", "0", "6.94", "Two", "0", "31.948", "0", "6.94", "Three", "0", "23.961", "0", "5.21"] The next step is to convert this array into a hash of arrays: hash ...

Tips for removing elements inserted with before() function

I have successfully implemented an alert-style div that is displayed when a user selects an option from a form and clicks the add to cart link. The jQuery .before() method is used to add the user's form selection to the div. I am facing two issues th ...

Effortlessly glide to a specific div ID upon page load using the URL address

One way to implement smooth scrolling to an anchor on page load is by using jQuery. Here's an example code snippet: $(function(){ $('html, body').animate({ scrollTop: $( $('#anchor1').attr('href') ).offset(). ...

Landing page experiencing issues with client-side setTimeout functionality

Good Afternoon, I am currently working on implementing a loading animation for the pages on my website. However, I am facing an issue with the client-side setTimeout function not functioning as expected. Interestingly, the same function works perfectly on ...

ngx-bootstrap - Convenient time selection tool for forms

I'm currently working with the time-picker component provided by ngx-bootsrap and I am looking to integrate the time-picker into an input box in a manner similar to how it is done with the date-picker (which can be seen in date-picker) https://i.ssta ...

Transferring data from one HTML element to another using Angular [Ionic]

My project involves utilizing an ionic slide box to display a series of images within it. <ion-slide-box> <!-- I am looping through the images based on the image count --> <ion-slide ng-repeat="n in [].constructor(imageCount) track by $in ...

Angular 18 mysteriously generating a fake routing error, even though the routes were functioning perfectly before

Issue: I've been working on integrating a login component with Google authentication in my Angular application. The user information is retrieved upon successful authentication, a token is generated, and then sent to the backend for further processing ...

Troubleshooting the issue with the Angular directive that adds another directive to decorate anchor tags

In an attempt to streamline my code, I've created a directive that automatically adds certain attributes to all anchor tags in a given list. This way, I don't have to keep duplicating the same code over and over again. While this approach has be ...

Creating a mask overlay that covers the entire screen while excluding a specific sibling div

My goal is to create a div that acts as a mask covering the entire window. It should have an opacity of 0.5 and a background color of lightgray. However, there is one particular div on the screen that I do not want to be affected by the mask. I attempted t ...

What methods can be employed to maintain a consistent width for a multi-line span that aligns with the content?

Inside a div, I have 2 spans. When the content of the first span is short enough to fit on one line, the span's width matches the text content and positions the second span next to it. If the content of the first span is long and causes it to wrap, t ...

Creating a stunning image carousel in Vue by integrating a photo API: step-by-step guide

Trying to figure out how to create an image carousel in Vue using photos from an API. Currently able to display the photos using: <section class="images"> <img v-for="image in images" :key="image.id":src="image.assets.large.url"> &l ...

What is the reason this switch statement functions only with one case?

Why is the switch statement not functioning properly? It seems to correctly identify the values and match them with the appropriate case, but it only works when there is a single case remaining. If there are multiple cases to choose from, nothing happens. ...

Eliminating the dependency on Angular $http in a custom JavaScript library

Is there a way to develop a versatile JavaScript library that can be utilized across different frameworks, while still being able to leverage Angular's $http service when necessary? Would it be feasible to incorporate jQuery as a fallback for other fr ...

The test may detect a variable that was not initialized

I'm trying to understand why I get the error message "variable may not have been initialized" when testing (variable === "some text"), but I don't receive the same error when using (typeof passwordHashOrg !== 'undefined') The code that ...

Mozilla puts an end to the default behavior of parent anchor tags

I am working with HTML code. In my HTML, the parent element is an anchor tag and the child element is a dropdown. I am trying to prevent the parent's default behavior. For example, when a user clicks on the dropdown, I want to trigger the dropdown ...

What is the purpose of returning a function in a React Hook?

Currently, I am incorporating Material-UI components into my project and have implemented the AutoComplete component in my application. While exploring an example provided by the Material-UI team, I stumbled upon a fascinating instance of using Ajax data ...

Retrieve individual items from a list of strings and store them in a new string variable

Recently delving into Java for the first time, I am faced with the following requirement: [{"candidate_id":"agent_4","cluster_ID":"To_Be_Added","count":"2","utterance":"Can I text ...