skip to Main Content

Given array:
const array = ["string1234","stringNew264"]

Result arrays should be like below arrays:

stringArray: ["string","stringNew"]
numbersArray: [1234,264]

I tried using split(), join(), foreach loop method but not getting proper result.

3

Answers


  1. You can use reduce method and regex to select according parts.

    const array = ["string1234","stringNew264"];
    
    const result = array.reduce((acc, cur) => {
      let stringPart = cur.replace(/[0-9]/g, '');
      let numberPart = Number(cur.replace(/[^0-9]/g, ''));
      
      acc.stringArray.push(stringPart);
      acc.numberArray.push(numberPart);
      
      return acc;
    }, { stringArray: [], numberArray: [] });
    
    console.log(result.stringArray); // ["string","stringNew"]
    console.log(result.numberArray); // [1234,264]
    Login or Signup to reply.
  2. Here is one approach. We can first split each array entry on (?<=D)(?=d), which will match the boundary between string and number. Then, use map() on the resulting array of arrays to generate the desired output.

    var array = ["string1234", "stringNew264"];
    var output = array.map(x => x.split(/(?<=D)(?=d)/));
    var strings = output.map(x => x[0]);
    var nums = output.map(x => x[1]);
    console.log(strings);
    console.log(nums);
    Login or Signup to reply.
  3. Maybe I went a little over the top here, but OP did not clearly specify in which order or how many strings and numbers can be expected in the array elements, I put together an alternative solution here that will collect all strings and all numbers from the array elements:

    var array = ["999string1234hello", "stringOnly","stringNew264abc77","123"];
    const strings=[],numbers=[], rxs=/(D+)/g,rxn=/(d+)/g;
    array.forEach(x=>{
     strings.push(x.match(rxs)??[]);
     numbers.push(x.match(rxn)??[]);    
    });
    
    console.log(strings);
    console.log(numbers);
    
    console.log("or, as flat arrays:")
    console.log(strings.flat());
    console.log(numbers.flat());
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search