1

We're trying to write a function that takes an array of strings and a separator, and joins all the strings separated by such separator.

We are not allowed to use the .join() method.

So far, I'm stuck trying to iterate though all the strings adding a separator between them each time.

I tried something like:

var aName = ['Frank','Vincent','Zappa'];


var join = (arr, separator = " ") => {
    for(var i = 0; i < arr.length; i++) {
        return arr[i] + separator + arr[i+1];
    }
};

join(aName, ' '); 

//output: "Frank Vincent"
//expected output: "Frank Vincent Zappa"

Thanks for your help.

3
  • In the for loop try with i<= arr.length Commented Feb 15, 2019 at 10:16
  • I've tried that, doesn't work. Commented Feb 15, 2019 at 10:20
  • Hello. Welcome to StackOverflow :). Your loop looks like it access elements out of bounds. Also, the logic of arr[i] + separator + arr[i+1]; will cause items to be repeated. Perhaps initalise a sting to the first element and the loop over the remaining elements and appending separator + arr[i]? Commented Feb 15, 2019 at 10:21

10 Answers 10

3

You can reduce the array:

function join(arr, separator)
{
    return arr.reduce((str, a)=> {return a+separator+str})
}
Sign up to request clarification or add additional context in comments.

2 Comments

const join = (arr, sep = " ") => arr.reduce((str, acc) => acc + sep + str); for a one-liner better using arrow function semantics :D
Actually I had an inkling that I could use reduce, but I had no idea how to even begin conceptualizing it. This is very cool. Thanks!
2

To fix your current code, try concatenating instead, and return only at the end:

var aName = ['Frank', 'Vincent', 'Zappa'];


var join = (arr, separator = " ") => {
  let result = '';
  for (var i = 0; i < arr.length; i++) {
    if (result) {
      result += separator;
    }
    result += arr[i];
  }
  return result;
};

console.log(join(aName, ' '));

1 Comment

Exactly what I was looking for. Everyone has been helpful, but this one takes the cake for showing me what I was doing wrong most clearly. Thanks a lot!
2

A very simple method is to append the separator only for the second element onwards:

const arr = ["Frank", "Vincent", "Zappa"];

const join = (arr, sep = " ") => {
  if (!arr || !arr.length) return "";
  let ret = arr[0];
  for (let i = 1; i < arr.length; i++) {
    ret += sep + arr[i];
  }
  return ret;
};

console.log(join(arr));
console.log(join(arr, "-"));

3 Comments

Perfect except when arr is empty.
@Amadan there, though I am sure there is a lot more error handling that could be done. OP's task really :) Also I'm not sure that the point of OP's exercise is to handle all edge cases such as calling join on a non-array…
Hey, why :) Now it's perfect. :D
2

You can use the String constructor

var name = ['Frank', 'Vincent', 'Zappa'];
console.log(String(name).replace(/,/g,' '))

3 Comments

@chiragRavindra, you can replace(',','') it with empty space
Though the array itself can contain strings containing commas @Chidambaram :)
@Chidambaram like this? const join = (arr = [], sep=' ') => String(arr).replace(/,/g,sep). But this oly works if the array items don't contain strings
1

You could check the length of the array first and return an empty string if length is zero.

Otherwise take the first element as start value for the result and iterate from the second element and add the separator and the value of the array.

Proceed until no more elements. Then return the result string.

var join = (array, separator = ' ') => {
        if (!array.length) return '';
        var result = array[0];
        for (var i = 1; i < array.length; i++) {
            result += separator + array[i];
        }
        return result;
    },
    array = ['Frank', 'Vincent', 'Zappa'];

console.log(join(array, ' '));

Comments

0

The problem with your code is that you use return in a for loop which means that function will stop it's execution and return a value you write in return.

To avoid that you should write something like this:

var name = ['Frank','Vincent','Zappa'];


var join = (arr, separator = " ") => {
    var result = '';
    for(var i = 0; i < arr.length; i++) {
        // adding to result string arr[i] and separator
        result += arr[i] + separator;       
    }
    // deleting separator in the end of string
    return result.slice(0, -1);
};

join(name, ' '); 

1 Comment

Thanks for your help! I realize now my mistake in returning something inside the loop.
0

To be precise it is not possible to create a string without join() since JavaScript will internally always call join() for arrays. But if you just want to create your own join() function you can iterate through the array, add a separator to your current item and do this until you reached the end where you only add your current item without a separator.

var name = ['Frank', 'Vincent', 'Zappa'];

function join(arr, separator = " ") {
    var str = "";

    if (arr.length === 0) return str;

    for (var i = 0; i < arr.length; i++) {
        str += i !== arr.length - 1 ?
            arr[i] + separator :
            arr[i];
    }

    return str;
};

console.log(join(name, ' '));

Comments

0

A solution using a curried function in es2015

const joinStrings = glue = ' ' => strings => {
  let res = '';
  strings.forEach(str => res += glue + str);
  return res.replace(glue, '');
}

const joined = joinStrings(', ')(['a', 'b', 'c']);
console.log(joined);

Comments

0

var names = ['Frank','Vincent','Zappa'];

const join = (names, separator) => {
  let str = '';

  for(let i = 0; i < names.length; i++) {
    str += (str ? separator : '') + names[i];
  }

  return str;
}

console.log(join(names, ' '));

Comments

0

function joinFunction(arr){
  let string = ''
 for( let char of arr ){
     string += char + ' '
 }
  console.log(string) 
}

joinFunction(['Frank','Vincent','Zappa']) 

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.