3

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.

Jack Bashford
  • 38,499
  • 10
  • 36
  • 67
HappyHands31
  • 3,503
  • 6
  • 40
  • 78
  • Can you explain your code? – PM 77-1 Apr 01 '19 at 21:55
  • The `for` loop should not be in the `else` clause, and the comparison in the `if` test should be `==` not `=` (`=` is for *assignment*). – Pointy Apr 01 '19 at 21:57
  • Sure I'm trying to say, if separator is defined, loop through the array to create a `newString` with the items in the array (`i`) + the `separator`. Then turn `newString` into a string and return it. – HappyHands31 Apr 01 '19 at 21:58
  • 1
    The code `if (separator = undefined)` is doing an assignation of variable separator to `undefined` value, not a comparison as you expect. – Shidersz Apr 01 '19 at 21:58

6 Answers6

6

try

array.reduce( (s,x,i) => s+(i>0 ? separator : '') + (x==null ? '' : x), '') 

function myJoin(array, separator=',') { 
  return array.reduce( (s,x,i) => s+(i>0 ? separator : '') + (x==null ? '' : x), '') 
}

console.log( myJoin(['a', 'b', 'c'], '+') ); 
console.log( myJoin(['Peter', 'Paul', 'Mary']) );
console.log( myJoin(['hello', undefined, 'world'], '-') );

We use here standard js functionalities: arrow functions, array reduce and ternary operator. If i>0 (not true only for first element) we add separator to output string s. If x is undefined or null we add to s empty string - or x value in other case.

Kamil Kiełczewski
  • 53,729
  • 20
  • 259
  • 241
2

A few hints:

  • Don't mix up the assignment (=) and comparison (===) operators. if(a = b) is a mistake in 99% of the cases.

  • array.toString() does call array.join() internally, I'd consider that as cheating, also I'm not sure what you want to achieve with that (I mean newString should already contain the wanted result if you do the loop correctly, shouldn't it?)

  • i is the index in your array to get the value at that position use array[i].

  • I don't think that your loop should be in the else { branch, I don't think you need that else at all (as you always want to join the array by looping over it).

  • with newString = you reassign newString and loose the previous value, you might want to use newString += to append a value to it.

Jonas Wilms
  • 106,571
  • 13
  • 98
  • 120
2

Use map and forEach with a template string like so:

function myJoin(arr, sep = ",") {
  arr = arr.map(e => [undefined, null].includes(e) ? "" : e);
  var result = "";
  arr.forEach((e, i) => result += `${i ? sep : ""}${e}`);
  return result;
}

console.log(myJoin(['Peter', undefined, 'Paul', null, 'Mary', 'Jack'], "-"));

ES5 syntax:

function myJoin(arr, sep) {
  sep = sep || ",";
  arr = arr.map(function(e) {
    return [undefined, null].includes(e) ? "" : e;
  });
  var result = "";
  arr.forEach(function(e, i) {
    result += (i ? sep : "") + e;
  });
  return result;
}

console.log(myJoin(['Peter', undefined, 'Paul', null, 'Mary', 'Jack'], "-"));
Jack Bashford
  • 38,499
  • 10
  • 36
  • 67
2

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], '.'));
David Alvarez
  • 870
  • 6
  • 17
  • Sorry but I do not understand the use of `...params` as the parameter. Can you please rewrite it with the parameters `array`, `separator` like in my code? – HappyHands31 Apr 01 '19 at 22:25
  • @HappyHands31 ...params takes all the parameters and form an array with it. But now it's even easier to understand with the two parameters – David Alvarez Apr 01 '19 at 22:30
  • Thank you - yeah now it's making sense, and it works. So then with your two `if-statements`, it's alternating between appending `array[i]` and `separator` to the `str`? Do `if-statements` alternate what they append by default then? – HappyHands31 Apr 01 '19 at 22:34
  • Also can you please explain `separator=','` as the initial second parameter - what if the user enters separator as `+` or `--`? – HappyHands31 Apr 01 '19 at 22:36
  • 1
    The first `if` checks if your value deserves to be appened to the string (not null and not undefined). The second `if` checks that if we are at the last item of the array, we don't put the separator (avoid having the separator at the end) – David Alvarez Apr 01 '19 at 22:36
  • 1
    separator=',' means "default value". Thus if you give only one parameter, separator will be set to ','. If you give 2 params, the ',' will be overriden by your 2nd param – David Alvarez Apr 01 '19 at 22:38
  • I see, yes I understand what they're checking for - I just did not know that consecutive `if-statements` alternate what they append to a new string. Interesting. – HappyHands31 Apr 01 '19 at 22:38
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/191068/discussion-between-davalres-and-happyhands31). – David Alvarez Apr 02 '19 at 08:35
2

Use default syntax to set the seperator || The a forEach taking in value, index, array Test for last element.

function myJoin (array, separator) {
  let newString = "";
  separator = separator||','; 
  
  array.forEach((a,i,arr) => {
    newString += `${a}${(i < arr.length-1) ? separator : ''}`;
  });
  return newString;
}

console.log(myJoin(['a', 'b', 'c'], '+'));
console.log(myJoin(['a', 'b', 'c']));
console.log(myJoin(['a', 'b', 'c'], '-'));
Bibberty
  • 4,282
  • 1
  • 6
  • 22
1

You can use Array.reduce() to join your array.

let arr = ['a', 'b', undefined, 'c', 'd', null, 'e'];

myJoin = (arr, separator = ',') =>
  arr.reduce((acc, val, i) =>
    acc + ([undefined, null].indexOf(val) >= 0 ? '' : val) +
    (i < arr.length - 1 ? separator : ''), "");

console.log('myJoin(arr): ', myJoin(arr));
console.log('myJoin(arr, "+"): ', myJoin(arr, '+'));
console.log('arr.join("+"): ', arr.join('+'));

Hope this helps,

Miroslav Glamuzina
  • 4,201
  • 2
  • 15
  • 30