Simba
Simba

Reputation: 275

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 ]

Upvotes: 2

Views: 216

Answers (3)

Nina Scholz
Nina Scholz

Reputation: 386604

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

Upvotes: 2

brk
brk

Reputation: 50291

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)

Upvotes: 0

CertainPerformance
CertainPerformance

Reputation: 370769

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

Upvotes: 1

Related Questions