简体   繁体   中英

how do i split numbers in a array ? javascript

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 ?

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.

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)

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM