1

Im trying to split all the numbers in a array:

var array_code = [116,101,120,116]; 

So i want the result to look like this: [1,1,6,1,0,1,1,2,0,1,1,6]

the code im working on right now looks like this:

var array_gesplit = new Array; 

for(var i=0; i< array_code.length; i++){
    console.log(array_code[i])
    while (array_code[i]) { 
        array_gesplit.push(array_code[i] % 10 );
        array_code[i] = Math.floor(array_code[i]/10);

    }
}

The result im getting from this is: [ 6, 1, 1, 1, 0, 1, 0, 2, 1, 6, 1, 1 ]

Who can help me ?

4 Answers 4

3

You can use Array.from() method for this:

var array_code = [116,101,120,116];
var result = Array.from(array_code.join(''), Number)
console.log(result)

Explanation:

  • array_code.join('') creates a string like "116101120116"
  • Array.from('116101120116') on this string results in new Array of strings like:
    • ["1", "1", "6", "1", "0", "1", "1", "2", "0", "1", "1", "6"]
  • We can also use Array.from() with map function, so that we can convert all these string values to Number in one line like:
    • Array.from(array_code.join(''), x => Number(x))
    • Or, just Array.from(array_code.join(''), Number)
    • The above logic result is the required output.
Sign up to request clarification or add additional context in comments.

1 Comment

Just as a side-note x => Number(x) is reducible to simply Number.
1

You can use flatMap() and convert number to string and use built-in split() method.

var array_code = [116,101,120,116]; 
const res = array_code.flatMap(x => x.toString().split('').map(Number));
console.log(res)

Comments

0

You could take strings and map numbers.

var code = [116, 101, 120, 116],
    result = code.flatMap(v => Array.from(v.toString(), Number));

console.log(result);

Comments

0

Here's a hack by using some details of the JavaScript language:

var array_code = [116, 101, 120, 116];
var array_string = JSON.stringify(array_code);
var array_parts = [].slice.call(array_string);
var parts = array_parts.slice(1, -1);  // get rid of the square brackets
console.log(parts);

1 Comment

That's not an array of numbers, it's an array of numeric strings and also ","

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.