简体   繁体   中英

How can I split array of Numbers to individual digits in JavaScript?

I have an array

const myArr = [ 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106 ]

I need to split into digits like this:

const splited = [ 9, 4, 9, 5, 9, 6, 9, 7, 9, 8, 9, 9, 1, 0, 0, 1, 0, 1, 1, 0, 2, 1, 0, 3, 1, 0, 4, 1, 0, 5, 1, 0, 6 ]

You could join the items, split and map numbers.

 var array = [ 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106], pieces = array.join('').split('').map(Number); console.log(pieces); 

Same approach, different tools.

 var array = [ 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106], pieces = Array.from(array.join(''), Number); console.log(pieces); 

map each number to a string and split the string, and spread the result into [].concat to flatten:

 const myArr = [ 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106 ]; const splitted = [].concat(...myArr.map(num => String(num).split(''))); console.log(splitted); 

You can use reduce function to create a new array and use split to split the number converted to string

 const myArr = [94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106] let newArr = myArr.reduce(function(acc, curr) { let tempArray = curr.toString().split('').map((item) => { return +item; }); acc.push(...tempArray) return acc; }, []) console.log(newArr) 

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