Search code examples
javascriptarraysstringfunctionseparator

Turn Array Into String, Separate String With Separator - JavaScript


Define a function, myJoin, that accepts up to two arguments:

  1. array
  2. separator (string, optional)

myJoin should return a string with all of the elements from the array joined together. The separator should separate the joined elements:

myJoin(['a', 'b', 'c'], '+'); // => "a+b+c"

If separator is undefined, use ',' as the default separator.

myJoin(['Peter', 'Paul', 'Mary']); // => "Peter,Paul,Mary"

If any elements in the array are undefined or null, they should be replaced with an empty string in the returned string.

myJoin(['hello', undefined, 'world'], '-'); // => "hello--world"

I can't use the built-in join method.

Link to codepen for testing

So far I have tried:

function myJoin (array, separator) {

  let newString = "";

  if (separator = undefined) {
    separator === ",";
  }

  else {

    for (let i = 0; i < array.length; i++) {
      newString = i + separator;
    }

  }

  newString = array.toString();

  return newString;

}

console.log(myJoin(['a', 'b', 'c'], '+'));

^ This is not combining the elements of the string together with the separator, and is actually returning a,b,c twice. Any idea why?

EDIT: First update to code after @Jonas Wilms' suggestions:

function myJoin (array, separator) {

  let newString = "";

  if (separator === undefined) {
    separator === ",";
  }

  for (let i = 0; i < array.length; i++) {
    newString += array[i] + separator;
  }

  return newString;

}

This seems to be working in my VS Code console but not in the CodePen.


Solution

  • function myJoin(array, separator=',') {
      let str = '';
      for (let i = 0; i < array.length; i++) {
        if (array[i] !== null && array[i] !== undefined)
          str += array[i];
        if (i < array.length - 1)
          str += separator;
      }
    
      return str;
    }
    
    console.log(myJoin(['a','b','c']));
    console.log(myJoin(['a','b','c'], '+'));
    console.log(myJoin(['a',null,'c'], '-'));
    console.log(myJoin(['a','b',undefined], '.'));