What is the best way to separate an array of numbers into individual digits using JavaScript?

I am looking to transform an array

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

into a new array with digits split 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 ]

Answer №1

One way to combine, split, and convert numbers in an array is by using different methods.

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

Another method that accomplishes the same task but uses different functions looks like this:

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

Answer №2

Transform each integer to a string, divide the string into substrings, and then use [].concat to combine them:

const myNumbers = [ 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33 ];
const divided = [].concat(...myNumbers.map(num => String(num).split('')));
console.log(divided);

Answer №3

To generate a new array, the reduce function can be utilized along with the split method to divide the number converted into a string.

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

let newArray = numbers.reduce(function(accumulator, current) {
  let tempArray = current.toString().split('').map((digit) => {
    return +digit;
  });
  accumulator.push(...tempArray)
  return accumulator;
}, [])

console.log(newArray)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to add a CSS style to any element that has the .btn:hover pseudo-class, except for those elements with the class '.dropdown-toggle'?

Is there a way to apply a style to all my .btn elements when hovering, except for those with the .dropdown-toggle class? I've tried a couple of methods but ran into some issues: attempt 1: .btn:not(.dropdown-toggle):hover { background-color: inher ...

What is the most effective way to condense these if statements?

I've been working on a project that includes some if statements in the code. I was advised to make it more concise and efficient by doing it all in one line. While my current method is functional, I need to refactor it for approval. Can you assist me ...

How to send a value to a function in Angular from a different function?

Within my Angular Typescript file, I am working with two functions named data and lists. My goal is to pass the variable windows from the function data to the function lists. However, when attempting to call the function lists, I encounter an error: Canno ...

Pattern Update Method: Iteratively updating each individual node

I'm struggling to grasp the concept of updating only those d3 nodes where the data has changed. Despite my efforts, I still can't seem to get it right. In the test example provided below, I am noticing that everything is being updated instead of ...

What is the process for verifying values?

My quiz includes various answers, with correct ones listed in the plist provided. <array> <dict> <key>QuestionTitle</key> <string>Eyelids are</string> <key>Answers</key> <array> ...

Display notification following successful data saving in CodeIgniter

I attempted to set up a notification to appear when saving data and displaying it in the view, but it didn't work as expected using notify.js. Can someone offer some assistance? This is my save function: function save() { $data = array( ...

Oops! An uncaught exception error occurred because the primordials were not defined

I used npm to install the package called aws-s3-zipper, but now I am encountering an error. This is the code snippet causing the issue: AWS = require("aws-sdk"); var S3Zipper = require("aws-s3-zipper"); function zipFolderOnS3() { var zipper = new S3 ...

Using AngularJS to fetch images from RSS feed description

I'm currently learning AngularJS by creating a simple RSS feed. I have successfully made a JSON request and fetched all the data including title, link, description, and images from the RSS feed I parsed. The code snippet for extracting images looks li ...

Creating a JSON array dynamically and appending elements to it during runtime

Is there a way to dynamically create multiple arrays at runtime in a program and have the ability to add data to a specific array when needed? button.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEven ...

Guide on Redirecting Response to a File using Co-Request module with NodeJs

I am utilizing Co-Request from this repository to fetch a Zip file from a URL, and the code I have for fetching it is as follows: The current code works fine. However, I'm facing difficulty in saving the response Zip file to an actual file. var co = ...

"An error was encountered with the JSON acceptance due to an

When I call an external json API, the response is coming back as JSON. If I don't specify the datatype as JSONP, the API fails due to an access control issue. I can successfully hit the API with Postman and receive the response. However, in the conso ...

Ways to eliminate a textbox from an HTML table using jQuery or JavaScript while retaining the textbox values

Currently, I am facing a task where I have a table with a column filled with textboxes. My goal is to eliminate the textboxes using jQuery/JavaScript while retaining the values within them. Here are a couple of methods I have attempted: // removes both t ...

Verify whether the element within an iFrame contains any content

After conducting extensive research, I have been unable to find a satisfactory answer to my question. Therefore, I am reaching out to see if anyone has the knowledge I seek. The Goal: I aim to check the contents within an iFrame and determine whether it ...

Uncovering the key based on the value in MongoDB

I'm currently working with Node.js using the express framework and Mongoose for MongoDB, and I've got a query regarding efficient data retrieval. Imagine having a mongo document structured like this: test : {a:1, b:2, c:2, d:1}; While it' ...

AngularJS Interceptors for secure page management

I recently started working with AngularJS and I'm facing an issue with my interceptor that catches 401 errors from server responses. When a 401 status is detected, it triggers a "loginRequired" message broadcast and redirects to the login page. Howev ...

HTML anchor tag failing to redirect to specified link

I need to populate the URI property from an API result into an HTML format. I attempted to achieve this by calling a function and running a loop 3 times in order to display 3 links with the URI property of each object. However, the code is not functioning ...

Succession of Mongoose queries

One interesting feature of my model is the ability to chain queries like find(), limit(), and skip(). However, there arises a question: How can I apply the limit or skip function to the output of Model.find() if the returning value does not inherently cont ...

Filter the object by its unique identifier and locate the entry with the highest score

I'm currently working on figuring out the proper syntax for sorting an object by ID and then identifying the highest score within that ID array. While I've managed to sort the object up to this point using conditionals and the sort() method, I&ap ...

Exploring the process of sending JSON responses through Express

I recently started working with node/express. My express app has a single post route ('/'), which is designed to retrieve information about GitHub users based on their usernames. For instance, when I make a post request like this { "develop ...

Using JavaScript to block form submission based on AJAX response

I am having trouble understanding why this code is not working as expected to prevent a submit. I have made sure all the HTML elements are properly linked and all alerts display correctly. It doesn't seem like I am losing scope on the event. If anyone ...