Joining Arrays and String with the join() and concat() Method

Guest Posts Paolo Nikko Nuñal

Here's another common array and string manipulation that is commonly used and often neglected since many programmers forget that there is a method that already exists and does this function. The method we are talking about is the join() and concat() method. These two methods both combines strings and arrays into one.

The first we are going to tackle about is the join() method. So you might ask, what does the join() method do? Easy it joins all the items in the array into one string.

Code


<script>
    var dataArray = new Array("John","Joe","Joseph");
    var names = dataArray.join();
    alert(names);
</script>


The variable names will contain a string of all the elements found on the dataArray. The default value in joining them or if you don't want to place a parameter, the elements will be separated with a comma ",". On the other hand if you want to separate it with something like say a ":" or a string like "and" all you have to do is place a parameter inside the method.

<script>
    var dataArray = new Array("John","Joe","Joseph");
    var names = dataArray.join("and");
    alert(names);
</script>


The above code will generate a string "John and Joe and Joseph".

The last one is the concat() method. Basically all it does is to join two arrays.

<script>
    var namesArray = new Array("John","Joe","Joseph");
    var carArray   = new Array("Toyota","Honda","BMW");
    var data = namesArray.concat(carArray); 

   alert(data); 
</script>


The value of the data array will be "John,Joe,Joseph,Toyota,Honda,BMW". The first array will be joined by the second array.