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.

4
  • Can you explain your code? Commented Apr 1, 2019 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). Commented Apr 1, 2019 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. Commented Apr 1, 2019 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. Commented Apr 1, 2019 at 21:58

7 Answers 7

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.

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

Comments

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], '.'));

8 Comments

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 ...params takes all the parameters and form an array with it. But now it's even easier to understand with the two parameters
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?
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)
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
|
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.

3 Comments

Please check out my most recent edit - I've tried to build off of as many of your hints as possible.
@happyHands31 you also add a seperator to the last item, resulting in "a,b,c," ...
So I would need to remove the last item from the array that I return? Using .pop() or .slice()?
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'], '-'));

1 Comment

Why would a working piece of code get a down vote without comment?
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'], "-"));

2 Comments

Do not use the built-in .join array method in your answer.
Fixed it @Keith.
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,

2 Comments

Using an array to check wether a value is either null or undefined is a bit overkill IMHO. val == null is just fine as undefined and null are loosely equal to each other.
@customcommander Yeah, I know, just force of habit by now I guess :/
1

One can use join.

let arr = [{id: 1, desc: 'desc1'}, {id: 2, desc: 'desc2'}];
let serialized = arr.map(x => JSON.stringify(x)).join('---');
console.log(serialized);

{"id":1,"desc":"desc1"}---{"id":2,"desc":"desc2"}

Comments

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.