Introduction
In this lab, we will be exploring the concept of joining elements of an array into a single string using JavaScript. We will be using the Array.prototype.reduce() method to combine the elements of the array and a separator to specify how the elements should be joined together. By the end of this lab, you will have a better understanding of how to manipulate arrays in JavaScript and create more efficient code.
How to Join an Array Into a String
To join all the elements of an array into a string, follow these steps:
- Open the Terminal/SSH and type
nodeto start practicing coding. - Use the function
join()with the following parameters:arr: the array to be joined.separator(optional): the separator to be used between the elements of the array. If not specified, the default separator,will be used.end(optional): the separator to be used between the last two elements of the array. If not specified, the same value asseparatorwill be used by default.
- The
join()function usesArray.prototype.reduce()to combine the elements of the array into a string. - The final string is returned.
Here's the code for the join() function:
const join = (arr, separator = ",", end = separator) =>
arr.reduce(
(acc, val, i) =>
i === arr.length - 2
? acc + val + end
: i === arr.length - 1
? acc + val
: acc + val + separator,
""
);
And here are some examples of how to use the join() function:
join(["pen", "pineapple", "apple", "pen"], ",", "&"); // 'pen,pineapple,apple&pen'
join(["pen", "pineapple", "apple", "pen"], ","); // 'pen,pineapple,apple,pen'
join(["pen", "pineapple", "apple", "pen"]); // 'pen,pineapple,apple,pen'
Summary
Congratulations! You have completed the Join Array Into String lab. You can practice more labs in LabEx to improve your skills.