Saturday 15 September 2018

JavaScript: concat(): concat arrays

Array.concat() method is used to concat elements of arrays.

Syntax
arr.concat(arr1, arr2, …arrN)
Above statement return new array by concatenating elements of arr, arr1, arr2,…arrN

Concat() method also takes elements and arrays in combincation.

var evens = [2, 4, 6, 8];
var odds = [1, 3, 5, 7, 9];
var primes = [2, 3, 5, 7, 11];
                          
var result1 = evens.concat(odds); // 2 4 6 8 1 3 5 7 9
var result2 = evens.concat(100, 101, primes); // 2 4 6 8 100 101 2 3 5 7 11

Observe below statement carefully. Concat() method concatenates arrays inside arrays also.

var result3 = evens.concat(1, [2, [3, 4]]); // 2 4 6 8 1 2 [3,4]

concat.html
<!DOCTYPE html>

<html>

<head>
    <title>Array Concatenation</title>
</head>

<body>
    <script type="text/javascript">
        function displayArray(arr) {
            for (var i = 0; i < arr.length; i++) {
                document.write(arr[i] + "  ");
            }
            document.write("<br />");
        }

        var evens = [2, 4, 6, 8];
        var odds = [1, 3, 5, 7, 9];
        var primes = [2, 3, 5, 7, 11];

        var result1 = evens.concat(odds); // 2 4 6 8 1 3 5 7 9 
        var result2 = evens.concat(100, 101, primes); // 2 4 6 8 100 101 2 3 5 7 11 
        var result3 = evens.concat(1, [2, [3, 4]]); // 2 4 6 8 1 2 [3,4] 

        displayArray(result1);
        displayArray(result2);
        displayArray(result3);
    </script>
</body>

</html>

Open above page in browser, you will get following text.

2 4 6 8 1 3 5 7 9
2 4 6 8 100 101 2 3 5 7 11
2 4 6 8 1 2 3,4



Previous                                                 Next                                                 Home

No comments:

Post a Comment