javascript array to string without commas

javascript array to string without commas

            //Method 1 - Array.join()
            //This is the simplest and quickest way to convert an array to a string without the commas. 
            //The join() method takes an optional separator string that is used to join the array elements into one string. 
            //If no separator is specified, a comma will be used.
            let myArray = [1, 2, 3, 4, 5]
            myArray.join("") //returns "12345"

            //Method 2 - Array.forEach()
            //The forEach() method is used to execute a function on each element in an array.
            //The function takes a parameter which will represent each element in the array as it iterates over it.
            //This parameter can be added to a new string which can be used to create the new string without the comma.
            let myArray = [1, 2, 3, 4, 5]
            let myString = ""
            myArray.forEach(element => {
                myString += element
            });
            myString //returns "12345"

            //Method 3 - Array.reduce()
            //The reduce() method also executes a function on each element in the array, but it returns a single value instead of an array.
            //This can be used to create a new string without commas by adding each element to the string as it iterates over the array.
            let myArray = [1, 2, 3, 4, 5]
            let myString = myArray.reduce((accumulator, currentValue) => {
                return accumulator + currentValue
            }, "");
            myString //returns "12345"
        

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe