Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

267
Views
Place every 2 strings into an array in an array in angular

I'm working with an angular project. I have a string like below and i sorted out all the special characters using regular expressions. Now, I want the first 2 strings to be in suare brackets and the second two in another square bracket like coordinates, and the output should be like below. Please help me achieve the functionality.

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

My ts code be like:


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

and my final output in result array is like:

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

Desired output

[ ["-1.23568", "75.87956"], ["-1.75682", "22.87694"] ]
about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

Another approach would be to use String.match() to get each group of coordinates, then Array.map() and String.split() to divide 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; }

about 4 years ago · Juan Pablo Isaza Report

0

You can avoid some complex regex logic and just, once you have:

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

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

Or if there are more than two pairs:

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))
}
about 4 years ago · Juan Pablo Isaza Report

0

For example you can use Array.prototype.splice(). This function can give you such 'portions' for your new array:

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

Juts loop through your initial array initialArr.length/2 times.

Working demo

EDIT: Or maybe you can update your replacing logic for getting not just number after number but pairs (for example '-1.23568 75.87956,-1.75682 22.87694') and then just split it twice.

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

and then loop and

split(' ')
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!