Home > other >  How to split numbers in an array into single digits
How to split numbers in an array into single digits

Time:03-21

In my code, I receive an array with numbers. Some numbers are double digits or even tree digits. So it looks like this:

 [48, 48, 48, 48, 99, 52, 50, 100, 97, 101, 102, 51, 98, 100, 49, 100, 51, 100, 52, 53, 54, 57, 99, 49, 53, 52, 55, 51, 55, 52, 100, 57, 99, 56, 52, 49, 99, 99, 102, 52, 56, 50, 51, 55, 53, 49, 56, 97, 53, 101, 99, 53, 55, 54, 99, 57, 50, 97, 99, 56, 97, 50, 53, 53, 49, 54, 52, 55, 50, 54, 56, 57, 56, 50, 54, 54, 57, 50, 53, 55, 48]

And this is the code how I've achieved this:

function hashData(s) {
let hashArray = []; 

for(let i = 0; i < s.length; i  ){
    let code = s.charCodeAt(i);
    hashArray.push(code);

}
hashArray.toString().split("")
console.log(hashArray)
return hashArray;

}

What I want to achieve is this:

[4, 8, 4, 8, 4, 8, 4, 8, 9, 9, 5, 2] //and so on.

As you can see I have tried the toString() method, but that doesn't seem to do anything.

CodePudding user response:

You could join and get a new array.

const
    values = [1, 23, 456, 7890],
    result = Array.from(values.join(''), Number);

console.log(result);

CodePudding user response:

Just .join the input numbers into one long string, then turn it back into an array (of individual characters) and map to number.

const hashData = s => [...s.join('')].map(Number);

console.log(hashData([48, 48, 48, 48, 99, 52, 50, 100, 97, 101, 102, 51, 98, 100, 49, 100, 51, 100, 52, 53, 54, 57, 99, 49, 53, 52, 55, 51, 55, 52, 100, 57, 99, 56, 52, 49, 99, 99, 102, 52, 56, 50, 51, 55, 53, 49, 56, 97, 53, 101, 99, 53, 55, 54, 99, 57, 50, 97, 99, 56, 97, 50, 53, 53, 49, 54, 52, 55, 50, 54, 56, 57, 56, 50, 54, 54, 57, 50, 53, 55, 48]))

CodePudding user response:

i heard some like splice() method, try that maybe ?

  • Related