Home > Back-end >  Place every 2 strings into an array in an array in angular
Place every 2 strings into an array in an array in angular

Time:11-06

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"] ]

CodePudding user response:

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(' ')

CodePudding user response:

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))
}

CodePudding user response:

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; }
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related