0

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));

0

5 Answers 5

1

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));

Sign up to request clarification or add additional context in comments.

Comments

0
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.

Comments

0

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));

Comments

0

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));

Comments

0
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"]));

1 Comment

I ended up using this. Thank you, everyone!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.