0

I am a javascript beginner, and here is the 5 coding problems that I am tackling with.

1.Declare a variable called myName and assign to an array populated with two strings: 1) your first name and 2) your last name.

2.Declare a function called join that can take two inputs: 1) an array and 2) a separator string. The separator string is optional.

3.join concatenates all the elements of the input array with the input string and returns the result. The output of join is always a string.

4.If no separator is provided, the default separator should be a string space ' '. If no input array is provided or the array is empty, join should return an empty string ''.

5.You cannot use the built-in join method for arrays and we highly recommend avoiding other built-in methods.


// I have written some codes below so far, and it seems I've completed 1~3. However, I have no clue to solve 4 and 5. How can I solve them?

// Error message said: The join function should default to using a space when a separator is not provided and should return an empty string if no array is provided

var myName = ["FirstName", "LastName"];

function join(arr,sep) {
  result = arr.join(sep);
  return result;
};
3
  • ` function join(arr=[],sep=' ') { let res = arr[0] || ''; for(let i=1;i<arr.length; i++){ result += ${sep}${arr[i]}; } return result; }; ` Ps: The homework question is not welcome in stackoverflow. Commented Mar 26, 2020 at 13:12
  • @ahuigo there is no official policy (that i can find at least) banning homework questions. Though I would recommend only hinting at a solution or providing resources for the student instead of providing a full solution. If a solution is provided it should be explained so the student learns something, which is why I upvoted Moosa Saadat's answer Commented Mar 26, 2020 at 13:37
  • @backcab Sorry for my arbitrary decision. I have edited this question with a more cleared title. Usefulness question is not welcome, not homework question. Commented Mar 27, 2020 at 0:58

5 Answers 5

1

4) You can set a default value for parameter which will be used when no value is passed:

function join(arr = [], sep = '') {
  if (arr.length === 0) {
        return "";
  }
};

5) If you cannot use the built-in method, you can write code of join yourself:

function join(arr, sep = '') {
  var result = "";
  for (let i = 0; i < arr.length - 1; i++) {
        result += arr[i];
        result += sep;
  }
  result += arr[arr.length - 1];
  return result;
};
Sign up to request clarification or add additional context in comments.

Comments

1

simply that ? :

let myName = ["FirstName", "LastName"];

function join(arr, sep) {
  arr = arr || [] 
  sep = sep || ' '
  let res = ''
  for(let i=arr.length;i--;) res = (i?sep:'') + arr[i] + res
  return res 
};
console .log( '--no args ------>' + join() + '<---')
console .log( 'myName  -------->' + join(myName) + '<---')
console .log( 'myName  * ------>' + join(myName,'/')+ '<---')
console .log( "['a','b','c']--->" + join(['a','b','c'],' = ')+ '<---')
.as-console-wrapper { max-height: 100% !important }

1 Comment

part 5 says don't use the built in join function
0
var myName = ["firstName", "lastName"];
// note the sep = " ", this is JS's default value syntax
// See: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Default_parameters
function join(arr, sep = " ") {
    // if arr is not an instance of an array
    // then we return an empty string as per the specs
    if (!(arr instanceof Array)) {
        return "";
    }
    // initialize the final string to an empty string
    var ret = "";
    // standard for loop for iterating through an array
    for (var i = 0; i < arr.length; i++) {
        // add the array element to the end of the return string
        // equivalent to ret = ret + arr[i]
        ret += arr[i];
        // if i is arr.length - 1, it's the last element of the array
        // so we don't want to add the separator
        if (i != arr.length - 1) {
            // but since it's not arr.length - 1 in this if statement
            // we can add the separator
            ret += sep;
        }
    }
    // we return the actual string
    return ret;
}

2 Comments

I'd hope the generous commenting is enough to learn. In the worst case, OP at least has to put in effort to delete the comments, in which case it's unfortunate he actively puts in effort to not learn anything.
This is true, hopefully they gain some insight from your efforts!
0

In your function you are using the join array method. If you are sure that that arr will always only have two elements then you could simply use the string concatenate character +, like so:

arr[0] + arr[1]

To make it more robust you could loop over the arr and add each element to the resulting output.

// Devine a variable to output
let output = '';
// Loop over the array elements
arr.forEach(el => {
  // Add eacht element to the existing output
  // The 'sep? sep + el: ' ' + el;' part checks if there is a seperator, if not add a space
  output += sep? sep + el: ' ' + el;
});

The above will only work if there is already an element added to the output, we will need to add a second check to see if the output is still an empty string.

The complete function would look something like this:

function join(arr, sep = '') {
  let output = '';
  arr.forEach(el => {
    if (output == '') {
      output += el;
    } else {
      output += sep? sep + el: ' ' + el;
    }
  });
  return output;
}

Then this would be the result:

var myName = ["FirstName", "LastName"];
join(myName, ', ') // 'FirstName, LastName'

Comments

0

let arr = ['a', 'b', 'c']
let string = ''
let separator = '-'
for(let i = 0; i < arr.length; i++) { 
    if(i !== arr.length - 1) {
       string += arr[i] + separator
    } else { 
       string += arr[i]
    }
}

//instead of the if else, you can remove
//the last character of the string after
//the loop is over (just keep 'string += arr[i] + separator' in the loop and remove 
//the last character of the string when the loop is over.

console.log(string)

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.