Tarah Perry
Tarah Perry

Reputation: 1

How to convert array into string without comma and separated by space in javascript without using .join()?

I am trying to find an alternative to .join(). I want to remove the "," and add a space. This is the desired output for myArray: Hey there

// create a function that takes an array and returns a string 
// can't use join()

// create array
const myArray = ["Hey", "there"];


/**
 * 
 * @param {Array} input
 * @returns {String}
 */

const myArraytoStringFunction = input => {
       // for (var i = 0; i < input.length; i++) {
       //     ????
       // } 
    return input.toString();
};

// call function
const anything1 = console.log(myArraytoStringFunction(myArray));

Upvotes: 0

Views: 78

Answers (5)

Tarah Perry
Tarah Perry

Reputation: 1

const myArraytoStringFunction = input => {
    let product = "";
    input.forEach(str => product += " " + str);\
    // original answer above returned this:
    // return product.substr(1); 
    // I used .slice() instead
    return product.slice(1); 
};

// This was another that I like - Thank you whomever submitted this
// I did change it a little bit)
// const myArraytoStringFunction = input => {
//     let product = "";
//     input.forEach((str, i) => product += i === 0 ? str : " " + str);
//     return product;
// };


console.log(myArraytoStringFunction(["I", "think", "it", "works", "now"]));
console.log(myArraytoStringFunction(["I", "win"]));
console.log(myArraytoStringFunction(["Thank", "you"]));

Upvotes: 0

Nina Scholz
Nina Scholz

Reputation: 386570

You could use reduce by using the accumulator for a check for adding the separator to the string.

const
    array = ["Hey", "there"];
    arrayToString = array => array.reduce((r, s) => r + (r && ' ') + s, '');

console.log(arrayToString(array));

Upvotes: 0

trincot
trincot

Reputation: 350252

Here is an alternative using recursion:

const myArray = ["Hey", "there"];
const myArraytoStringFunction = inp => 
     (inp[0] || "") + (inp.length>1 ? " " + myArraytoStringFunction(inp.slice(1)) : "");
const anything1 = console.log(myArraytoStringFunction(myArray));

Upvotes: 0

Niles
Niles

Reputation: 351

const myArraytoStringFunction = function myArraytoStringFunction(input) {
    let r = "";
    input.forEach(function(e) {
        r += " " + e;
    }
    return r.substr(1);
};

I'm assuming you're avoiding join because it's a homework assignment, so I didn't use reduce, which they probably haven't gotten to yet.

Upvotes: 0

CertainPerformance
CertainPerformance

Reputation: 370729

You might use reduce, adding a space if the accumulator is not empty:

const myArray = ["Hey", "there"];
const myArraytoStringFunction = input => input.reduce((a, item) => (
  a + (a === '' ? item : ' ' + item)
), '');
console.log(myArraytoStringFunction(myArray));

Upvotes: 1

Related Questions