7

I have a problem with my code. I have a series of string. For example I made this:

var a = 12345678

I want to split these string into an array, so that it will produce something like this:

[12,23,34,45,56,67,78]

I already tried this code:

var newNum = a.toString().match(/.{1,2}/g)

and it returns this result instead of the result I wanted

[12,34,56,78]

Are there any solution to this? Thanks in advance.

1
  • Start with a simple for loop or array processing method. You can't do this with regex alone Commented Apr 6, 2019 at 13:16

9 Answers 9

7

Updated answer to address the question body

'1234567'.split('').map((e,i,a) => a[i] + (a[i+1] ?? '')).slice(0,-1);
// Array(6) [ "12", "23", "34", "45", "56", "67" ]

Original answer

Edit: I see now this doesn't answer the problem described in the question body. I'll leave it though, as the problem it solves may well be described by the question title.


Shortest way:

'abcdefg'.split(/(..)/g).filter(s => s);
// Array(4) [ "ab", "cd", "ef", "g" ]

Explanation: split(/(..)/g) splits the string every two characters (kinda), from what I understand the captured group of any two characters (..) acts as a lookahead here (for reasons unbeknownst to me; if anyone has an explanation, contribution to this answer is welcome). This results in Array(7) [ "", "ab", "", "cd", "", "ef", "g" ] so all that's left to do is weed out the empty substrings with filter(s => s).

Sign up to request clarification or add additional context in comments.

2 Comments

'abcdefg'.match(/(..)/g) is an even shorter version, though is not what Mohammand asked for.
@luvejo Fair point. I updated the answer, adding a functional approach to the problem described in the question body.
3

Hope this helps.

var a = 12345678;
a= a.toString();
var arr=[];
for (var i =0; i<a.length-1; i++) {
 arr.push(Number(a[i]+''+a[i+1]));
}

console.log(arr);

Output

Comments

3

You could use Array.from() like this:

let str = "12345678",
    length = str.length - 1,
    output = Array.from({ length }, (_,i) => +str.slice(i, i+2))

console.log(output)

Here's a generic solution for getting varying size of chunks:

function getChunks(number, size) {
  let str = number.toString(),
      length = str.length - size + 1;
      
  return Array.from({ length }, (_,i) => +str.slice(i, i + size))
}

console.log(getChunks(12345, 3))
console.log(getChunks(12345678, 2))

1 Comment

works, but can you please explain this Array.from({ length }, (_,i) => +str.slice(i, i+2))
0

We can do this using Array.reduce :

  • Firstly, convert the number into a string and then split it into an array
  • Secondly, apply reduce on the resulting array, then append current element ele with the next element only if the next element exists.
  • Lastly, after the append is done with the current and next element convert it back to a number by prefixing it with an arithmetic operator + and then add it to the accumulator array.

var a = 12345678;

const result = a.toString().split("").reduce((acc, ele, idx, arr) => {
  return arr[idx + 1] ? acc.concat(+(ele + arr[idx + 1])) : acc;
}, []);
console.log(result);
console.assert(result, [12,23,34,45,56,67,78]);

Comments

0

Another approach, using reduce

var a = 12345678
a.toString()
 .split('')
 .reduce((c,x,i,A)=>i>0?c.concat([A[i-1]+A[i]]):c,[])

Comments

0

The pattern is start with the first two digits (12) and then add eleven until you have an array that ends with the last digit of the input string (8).

let str = `12345678`;

const eleven = string => {
  let result = [];
  let singles = string.split('');
  let first = Number(singles.splice(0, 2).join(''));
  for (let i = 0; i < string.length-1; i++) {
    let next = 11 * i;
    result.push(first+next);
  }
  return result;
}
    
console.log(eleven(str));

Comments

0
var a = 12345678;
console.log(
  String(a)
    .split("")
    .map((value, index, array) => [value, array[index + 1]].join(''))
    .map(item => Number(item))
);

output  - [ 12, 23, 34, 45, 56, 67, 78, 8 ]

explanation

  • String(a) - convert your number value 'a' into string, to prepare for operations
  • split("") - convert string value into array
  • .map((value, index, array) => [value, array[index + 1]] ...

for every item from array, take current value and next value, and put them into array cell

  • .join('')) - then create string from this array value like this [ '1', '2' ] => ['12']

  • .map(item => Number(item)) - at the end, convert every array item into number.

Comments

0

You could use a recursive approach. Here I used an auxiliary function to perform the recursion, and the main function to convert the number to a string.

See example below:

const arr = 12345678;

const group = a => group_aux(`${a}`);
const group_aux = ([f, s, ...r]) =>
  !s ? [] : [+(f+s), ...group_aux([s, ...r])];

console.log(group(arr));

Comments

0

If order doesn't matter, a more legible solution is:

let even = '12345678'.match(/(..)/g)
let odd = '2345678'.match(/(..)/g)
let result = [...even, ...odd]

If order does matter, just use .sort():

result.sort()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.