0

I have a string ' 1 22 333 4444 5 6 ', and I want ot make an array like this - [[1, 22], [22, 333], [4444, 5], [5, 6]];

I tried to use for... loop but it didn't help.

let str = ' 1 22 333 4444 5 6 ';
let arr = [];
for(let i = 0; i < str.length; i++)
 arr.push(str.slice(str.indexOf(' ', i),str.indexOf(' ',i+1)));

And it gave this output:

[ ' 1', '', ' 22', '', ' 333', '', ' 4444', '', ' 5', '', ' 6', '', '' ]

Instead of: [[1, 22], [22, 333], [4444, 5], [5, 6]];

Why is it wrong? Does anybody know how to do it?

asked Aug 30, 2018 at 13:58
3
  • Do you really want that last array to have [5, 6] or just [6] since the original string only had one 5 in it? Commented Aug 30, 2018 at 14:00
  • 6
    Whty not [333,4444] Commented Aug 30, 2018 at 14:00
  • using regex would be smooth. Commented Aug 30, 2018 at 14:12

8 Answers 8

3

Based on the question, the format of the output is not clear. You can do it in few ways depending on the desired format of the output:

1) if you want every last item to be the first item of the next chunk

const input = ' 1 22 333 4444 5 6 ';
const result = input.trim().split(' ').map(Number).reduce((all, n, i, arr) => i ? [...all,[arr[i-1],n]] : [] ,[])
console.log(result);

2) if you want to split it in chunks of two

const input = ' 1 22 333 4444 5 6 ';
const result2 = input.match(/(\d+ \d+)/gi).map(a => a.split(' ').map(Number));
console.log(result2);

answered Aug 30, 2018 at 14:14
Sign up to request clarification or add additional context in comments.

Comments

2

const res = ' 1 22 333 4444 5 6 '
 .split(' ')
 .filter(Boolean)
 .map(v => [v])
 .reduce((acc, curr, idx) => {
 acc = idx % 2 ? [...acc.slice(0, acc.length-1), acc[acc.length-1].concat(curr)] : [...acc, curr];
 return acc;
 }, []);
 
console.log(res);

answered Aug 30, 2018 at 14:18

Comments

1

It is not possible to do what you would like to do because the delimiter between each of the numbers is consistent for the entire string. You need to have one delimiter for each of the numbers, then a different delimiter for the groups.

For example;

let str = '1 22,333 4444,5 6';
let groups = str.split(",");
let arr = [];
for (let i = 0; i < groups.length; i++)
 arr.push(groups[i].split(" "));
 
console.log(arr);

answered Aug 30, 2018 at 14:05

5 Comments

result arrays not integer values
@NickA Perhaps that was an overly broad claim, but I try not to assume that the original poster wanted this in groups of two explicitly as one could reasonably assume that the groups of two were coincidental.
@AdamChubbuck I didn't notice something in the comments, just ignore me :)
@AdamChubbuck Although it's likely safe to assume that the groups of 2 are not coincidental due to: str.slice(str.indexOf(' ', **i**), str.indexOf(' ',**i+1**))
@NickA Perhaps the OP can clarify.
1

As an alternative you could use a regex with a capturing group and positive lookahead to assert what follows are one or more digits and capture that in the second capturing group.

(\d+) (?=(\d+))

Then add group 1 and group 2 in an array to arr.

const regex = /(\d+) (?=(\d+))/g;
let m;
let str = ' 1 22 333 4444 5 6 ';
let arr = [];
while ((m = regex.exec(str)) !== null) {
 arr.push([m[1], m[2]]);
}
console.log(arr);

answered Aug 30, 2018 at 15:07

Comments

0

Maybe like this:

let str = ' 1 22 333 4444 5 6 ';
let arr = [];
let str_arr=str.split(' ');
for(let key in str_arr){
 if(str_arr[key]!=''){
 	 let add_arr=[];
 	 add_arr.push(parseInt(str_arr[key],10));
 	 let next_key=parseInt(key,10)+1;
 	 if(str_arr[next_key]){
 	 	add_arr.push(parseInt(str_arr[next_key],10));
 	 arr.push(add_arr);
 	 }
 }
}
console.log(arr);

answered Aug 30, 2018 at 14:10

Comments

0

You should run this code

let str = ' 1 22 333 4444 5 6 ';
let arr = [];
var res = str.split(" ");
console.log(res);
var a = res.filter(i => i !== "");
console.log(a);
var tempArr = [];
var counter = 0;
for (var i = 0; i < a.length; i++){
 counter++;
 tempArr.push(a[i]);
 if(counter == 2){
 arr.push(tempArr);
 tempArr = [];
 counter = 0;
 }
}
console.log(arr);
answered Aug 30, 2018 at 14:11

Comments

0

If I interpret the task right, this is one way you can solve it:

' 1 22 333 4444 5 6 '
 .trim()
 .split(' ')
 .reduce((arr, item, index) => {
 if (index % 2 === 0) {
 arr.push([ item ]);
 } else {
 arr.slice(-1)[0].push(item);
 }
 return arr;
 }, [])
answered Aug 30, 2018 at 14:31

Comments

0

let str = ' 1 22 333 4444 5 6 ';
let arr = [];
let temp = str.trim().split(" ");
for (let i = 0; i < temp.length - 1; i++)
 arr.push([parseInt(temp[i]), parseInt(temp[i + 1])]);
console.log(arr);
for (let i = 0; i < arr.length - 1; i++) {
 console.log(arr[i]);
}

the output of above code is

[[1, 22], [22, 333], [4444, 5], [5, 6]]
[1, 22] 
[22, 333]
[4444, 5]
[5, 6]
Adam Chubbuck
1,71015 silver badges32 bronze badges
answered Aug 30, 2018 at 14:12

1 Comment

"the output of above code is" ... No it's not, you dropped [333, 4444]

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.