Guidelines for converting a number into an array of strings using JavaScript

Task: Write a function that takes a number and returns an array of strings, each element being the number cut off at each digit. Examples: For 420, the function should return ["4", "42", "420"]; For 2017, the function should return ["2", "20", "201", "2017"]

I've written some code to solve this problem, but I'm looking for a more concise solution without using push method. It took me quite a while to figure out a declarative approach. Thank you.

function createArrayOfTiers(num) {
    const arrT= num.toString().split("");
    let z = [];
    const result = arrT.reduce((acc, curr) => {
        acc += curr;
        z.push(acc);
        return acc;
    }, "");
    
    return z;
}

Note: The input will always be an integer within the range [0, 1000000]

Answer №1

To convert a string into an array and maintain previous characters, you can utilize a closure in JavaScript.

Array.from is designed to work with iterables, where both the string and resulting array contain individual characters as values.

The code snippet below demonstrates how a closure can be used within the mapping process. This closure initializes with an empty string and appends each character to build the resulting array elements. The variable v represents an element of the array being transformed, similar to how a typical Array#map callback works.

Array.from(
    number.toString(),          // take iterables
    (s => v => s += v)('')      // map value of array with the previous elements
)

const getParts = number => Array.from(number.toString(), (s => v => s += v)(''));

console.log(getParts(2017));

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

Guide to enabling cross-domain uploads of files

After following a tutorial, I successfully implemented an HTML5 uploader on my website. The source of the tutorial can be found here: The uploader works perfectly; however, I am now facing an issue where I want to upload files to a different domain. Accor ...

Creating multiple asynchronous calls within a loop in JavaScript

I am currently working on a task in my gulpfile.js that involves uploading an app using Gulp and SharePoint. 'use strict'; const gulp = require('gulp'); const build = require('@microsoft/sp-build-web'); const spsync = require ...

What is the best way to identify different directives within the same $scope?

When it comes to calling directive functions from controllers, I follow this approach: function myControllerFunction = function () { $scope.highlight(); } The highlight() function is defined within the directive itself. But what if there are two dif ...

How can I place the current date inside a red dashed box with text using JavaScript?

Let's Solve This: The date currently appears in the top left corner without any special formatting. My goal is to make it bold, red, and encased in a dashed-red border. I have identified the element by its ID "datetext", corresponding to a "p" tag w ...

The reason behind a loop being caused by an IF statement

Here is a snippet of code that I'm trying to understand: ReactDOM.render(<Change />, document.getElementById('app')); function Change() { const [i, setI] = React.useState(0); let rnd = 9; if (i !== rnd) { setTime ...

Subsequent $http requests become trapped in a pending state and eventually fail with a NodeJS server

I encountered a strange issue with Angular and Node that I can't seem to find a solution for. In my Angular controller, I have a function that fetches data initially and stores it in $scope. This function also allows the controller to make a POST req ...

Can you explain the functionality of $on.constructor in AngularJS?

Recently, I attempted an XSS challenge on the PortSwigger labs website. You can find the challenge here. This is my solution to the XSS challenge: {{$on.constructor('alert(1)')()}} However, since I have no prior experience with AngularJS, I&apo ...

What are the steps to update content by referencing an id in the hash URL?

Currently, I am utilizing the following code snippet to extract an ID from the hash URL: var integer = window.location.hash.match(/\d+/) | 0; alert(integer); However, I have encountered an issue where upon using the back button after modifying the U ...

Error encountered in Three.js: ShaderPass.js is unable to read the property 'prototype' of undefined

I'm currently facing an issue while trying to implement a basic GlitchPass in a Three.js demo. I keep encountering the error message Uncaught TypeError: Cannot read property 'prototype' of undefined at ShaderPass.js. For this particular dem ...

What is the best way to compare two fields in react?

Good afternoon, I am currently working on a datagrid using the MUI datagrid and following the MUI Guide. I have encountered an issue where I included two fields with the same name because I needed two separate columns (one for the date and one for the nam ...

Issue encountered during app creation using the command line interface

After successfully installing nodejs and checking the versions of nodejs, npm, and npx, I proceeded to run the command npm install -g create-react-app which executed without any issues. However, when I attempted to create a new React app using create-react ...

Iframe navigation tracking technology

Let's say I have an iframe element in my HTML document. <html> <body> This is my webpage <button> Button </button> <iframe src="www.example.com"></iframe> </body> </html> If a user clicks on links wi ...

Retrieve combination values through an AJAX request using ExtJS

My UI is developed using ExtJS, and I have a specific set of tasks that need to be executed when the page loads: Initiate an ajax call to the server to fetch a HashMap. Create a combobox within the main Panel on the page. var combo = Ext.create(' ...

Extract JSON data from Python API

Currently, I am delving into web programming and have created a Python API that queries an SQL database to return a JSON. The functionality of the API is as expected. In parallel, I've developed a controller where I execute a GET request to utilize t ...

When attempting to invoke the rest function, an error occurs stating that the dataService.init in Angular is not

Learning AngularJS has been my current focus. To practice, I have been working on a Quiz app tutorial. However, I encountered an issue when trying to call the rest function of a factory after injecting it into one of my controllers. The JSON data for this ...

Is it possible to display a combination of images and text data using JQUERY/AJAX, when the data is sent as objects or arrays?

I'm struggling to figure out how to handle an object or array sent from a server that contains binary picture and text data using JQUERY/AJAX Here is the server-side setup: const url= require('url'), express = require('express&ap ...

ReactJS safeguarded route redirection/refresh obstacle

Utilizing react and react-router-dom: import React from 'react'; import { Switch, Route, Redirect } from 'react-router-dom'; To secure a route with the following: Router const Router = () => { return ( <Switch> ...

In what circumstances should one utilize either the "this" keyword or an event argument?

$("span").on("click",function(event){ event.stopImmediatePropagation(); }) $("span").on("click",function(event){ $(this).stopImmediatePropagation(); }) Can you explain the distinction between these two code snippets and why only one of them is ...

Combining various JSON objects by nesting them together

I'm in the process of creating an endpoint where I need to combine data from four different tables into one nested object. Each table record is retrieved in JSON format using sequelize - they include information on location, service, staff, and tenant ...

At the ready stance for a particular grade of students attending a class

I have created a page with a navigation menu that can be scrolled using the wheel mouse. My goal is to ensure that the li item with the 'selected' class is always positioned in the first position on the left. Is there a way to achieve this using ...