What steps can I take to ensure that my 'for loop' properly returns the characters I want to push?

Currently, I am in the process of expanding my knowledge of JavaScript. As I delve into challenges on Codewars, it has become evident that there are gaps in my understanding. One particular challenge I faced involved formatting a phone number using a 'for loop' to push characters into an array. Despite numerous attempts at different solutions, I have yet to achieve the desired outcome. Any guidance on identifying errors in my approach and addressing the flaws in my logic would be greatly appreciated. Below is my best attempt so far:

const createPhoneNumber = (phoneNumber) => {
    let formattedNumber = [];
    formattedNumber.push(phoneNumber)
    for (let i = 0; i < formattedNumber.length; i++) {
        if (formattedNumber[i] === 0) {
            formattedNumber.push('(')
        }
        if (formattedNumber[i] === 2) {
            formattedNumber.push(')')
        }
        if (formattedNumber[i] === 5) {
            formattedNumber.push('-')
        }
    }
    return(formattedNumber.toString());
}

console.log(createPhoneNumber(1234567890));

Answer №1

Here are some suggestions:

  • Instead of inserting one item into the array
    formattedNumber.push(phoneNumber)
    and looping through it, try converting the number to a string and iterating using its length
  • The check formattedNumber[i] === 0 is comparing the value to 0, but you want to compare the index, so change this to i === 0
  • Use .join('') instead of toString() to join the characters back together at the end of the function

const createPhoneNumber = (phoneNumber) => {
    const phoneNumberStr = (phoneNumber).toString(); 
    let formattedNumber = [];
    for (let i = 0; i < phoneNumberStr.length; i++) {
        if (i === 0) {
            formattedNumber.push('(')
        }
        if (i === 2) {
            formattedNumber.push(')')
        }
        if (i === 5) {
            formattedNumber.push('-')
        }
        formattedNumber.push(phoneNumberStr[i]);
    }
    return(formattedNumber.join(''));
};

console.log(createPhoneNumber(1234567890))

You can also use .reduce() for the same purpose, which iterates through an array and passes a value from one iteration to the next:

const createPhoneNumber = (phoneNumber) => 
    (phoneNumber).toString().split('').reduce((acc, char, i) => {
      let pre = ''; 
      if (i == 0) { pre = '('; }
      if (i == 2) { pre = ')'; }
      if (i == 5) { pre = '-'; }
      return `${acc}${pre}${char}`;
    }, '');

console.log(createPhoneNumber(1234567890));

By the way, your question may have been downvoted due to lack of expected output or error details 😉

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

Issue encountered while attempting to save a value in localStorage

I am encountering an issue while trying to save and read the value of a button in the panel. The error message I receive is - Unable to set property 'adl' of undefined or null reference. This is my first time working with localStorage, so I' ...

The debugging functionality in WebStorm version 11.0.4 is currently experiencing problems. Users have reported receiving a warning message stating that the commands node --debug and node --debug-br

Specific warning message: Warning: node --debug and node --debug-brk are no longer supported. Please use node --inspect or node --inspect-brk instead. Node version: 8.9.3 Does anyone know of a workaround to enable seamless debugging in the IDE? Any a ...

How to choose a javascript drop down using selenium?

Here is the HTML code for a JavaScript drop-down menu that contains various options, including "All Resumes". I am attempting to select this option using Selenium WebDriver: <div id="resume_freshness_container"> <div class="dropdown_small_wrapper ...

How can I use jQuery to add animation to the coloring of an SVG graphic?

I want to create a dynamic animation for my SVG using jQuery. I aim to first animate the path of the SVG, and then after the initial animation, I would like to animate the fill of the SVG with specified duration and easing function. Is it possible to achi ...

Experiencing difficulty in rendering API within React component

Trying to display an image from a specific API that I came across here. However, encountering the following error in the console... Error with Fetch API: TypeError - this.state.dogs.map is not functioning properly. Code snippet provided below: <htm ...

Using Pandas to Substitute an Integer Substring with a Different Value

Is there a way to decrease the first integer in a string by 1? Here is the dataframe I am working with: No pl. Expected B2bb-hb 0.56 0.35 F378cq-h1 0.21 0.62 W30mm2-fpr2 8.17 0.76 Z51m ...

Query key array failing to update when key is modified

Encountering an issue with the query key array not updating when the selected warehouse ID is changed. This causes useQuery to use outdated data instead of fetching new data for the updated warehouse ID. Struggling to figure out how to update the query k ...

"Utilizing Jquery to extract data from a form field and combine it with a URL for maximum value

Today, I am delving into the world of jQuery for the first time and finding myself in need of some assistance with a particular problem. While this issue may seem trivial to experienced individuals, it is posing quite a challenge for me. The dilemma lies ...

Issues with Fetch API and CORS in Web Browsers

Hello, I'm encountering an issue related to CORS and the Fetch API when using browsers. Currently, my setup involves running a NodeJS server built with Express on localhost:5000. This server responds to a GET request made to the URL /get_a, serving ...

Implementing the move() function in a paddle-based game

Currently working on the move() method for the ball class in my paddle game. This paddle game features a paddle at the bottom that can move left and right, with the ball bouncing off three walls. I have realized that my current move method is not working p ...

What is the most effective method to guarantee the creation of an object prior to navigating through the code that relies on it?

I recently encountered an issue with my code that utilizes fetch() to retrieve and convert .tiff images into an html5 canvas for display in a browser using tiff.js (https://github.com/seikichi/tiff.js/tree/master). While the functionality mostly works as i ...

Accessing geographical coordinates using Google Maps API with JavaScript

Hey there, I could really use your assistance. I'm looking to integrate a localization map on my website to track user locations. Any idea how I can go about doing this? Thanks in advance! ...

Text Parallax Effect

For my website, I am interested in incorporating a unique parallax effect. Instead of just fixing a background image and allowing scrolling over it, I want to apply this effect to all of the content on my site. The website consists of a single page with m ...

Guide to making a Color Palette Array

Is it possible to create a Color array to store various color values? public static Color[] colors; public void setColor() { colors=new Color[3]; colors[0]=R.color.disableColor; } Below is the color.xml file: <?xml version="1.0" encoding="ut ...

Eliminate repeated elements within a JSON dataset to create a consolidated array

Looking to extract unique data from the JSON object below in order to create a result json with a list of questions and their corresponding choices. Any assistance would be greatly appreciated. Thanks in advance..!! var data = [ { "category": "s ...

Pause for a moment before commencing a fresh loop in the FOR loop in JavaScript

Behold, I present to you what I have: CODE In a moment of curiosity, I embarked on creating a script that rearranges numbers in an array in every conceivable way. The initial method I am working with is the "Selection mode", where the lowest value in th ...

Ways to restrict the frequency of additions to an array or CSV file in a text-based Spotify system

I am currently working on a text-based Spotify program in Python after being inspired by a friend who has a similar task for school. One of the tasks I have is to create random playlists, and I am struggling with generating a playlist by genre. Task 5a: C ...

Unable to render canvas element

Hey guys, I'm trying to display a red ball on the frame using this function but it's not working. I watched a tutorial and followed the steps exactly, but I can't seem to figure out what's wrong. Can someone please help me with this? I ...

Trouble with Express.js and Mongoose: Issue with find() method not returning results for specified variable

For the task I'm working on, my goal is to display items that are only visible to the user who posted them. To manage sessions, I am using Passport.js. The code I have written seems to be functioning well up until the end. app.get('/latestp ...

Changing a variable with Functions and Objects

I'm curious to know what the index variable returns in this code snippet. I believe it will be 0. function jsTest() { var index = 0; var counter = 0; var obj = {}; obj.index = index; var func = function () { for (index ...