Skip to main content
Inspiring
June 2, 2016
Answered

concatenating arrays

  • June 2, 2016
  • 1 reply
  • 203 views

Hello again. I'm trying to combine two complete arrays using JS, and am borrowing from a script I found (in red).  The goal is to end up populating the variable "bothArrays" with all 6 animals separated by commas.

1.

var firstArray= [ "cat", "dog", "snake" ];

var secondArray = ["frog","cow","eagle"];

window.cpAPIInterface.setVariableValue(bothArrays, firstArray.concat(secondArray));

Thanks to others on this board, I realize how to do this a long way -

2.

var firstArray = [ "cat", "dog", "snake" ];

var secondArray = ["frog","cow","eagle"];

window.cpAPIInterface.setVariableValue( "bothArrays", firstArray[ 0 ] + ", " + firstArray[ 1 ] + ", " + firstArray[ 2]+ ", " + secondArray[ 0 ]+ ", " + secondArray[ 1 ]+ ", " + secondArray[ 2 ]);

Could someone please point out the error in my first shorter attempt?

    This topic has been closed for replies.
    Correct answer Lilybiri

    The concat() method will create a new array which has all the elements of two arrays. That is not what you want, at least if your second work flow results in what you expect.

    var botharrays =  firstArray.concat(secondArray);

    This would result in:

    ["cat", "dog", "snake", "frog","cow","eagle"] as content of the last array. But you cannot store an array in one Captivate variable.

    1 reply

    Lilybiri
    LilybiriCorrect answer
    Legend
    June 2, 2016

    The concat() method will create a new array which has all the elements of two arrays. That is not what you want, at least if your second work flow results in what you expect.

    var botharrays =  firstArray.concat(secondArray);

    This would result in:

    ["cat", "dog", "snake", "frog","cow","eagle"] as content of the last array. But you cannot store an array in one Captivate variable.