-3

I have two jQuery variables. Each variable is a text string containing words separated by a comma.

var myFirstVariable = green,blue
var mySecondVariable = circle,triangle

I would like to have a third variable retured like this:

var myThirdVariable = greencircle,bluecircle,greentriangle,bluetriangle

The order of the words in myThirdVariable is not important. But my first two variables can contain any number of words, so if

var myFirstVariable = green,blue,yellow
var mySecondVariable = circle,triangle,square

Then I need my third variable to returned like this:

var myThirdVariable = greencircle,bluecircle,yellowcircle,greentriangle,bluetriangle,yellowtriangle,greensquare,bluesquare,yellowsquare

I think I need to push() both variables into an array but I'm struggling with this area of jQuery. Hope someone can shed some light on this. Many thanks.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
Vin
  • 1,975
  • 5
  • 27
  • 34

4 Answers4

3

I'm struggling with this area of jQuery

That's simply because the jQuery library has no tools for this kind of work.

Use the native JavaScript functionality instead, specifically the String split method, the Array join method, the string concatenation operator + and for-loops:

var myFirstVariable = "green,blue"
var mySecondVariable = "circle,triangle";

var firstArr = myFirstVariable.split(","),
    secondArr = mySecondVariable.split(","),
    thirdArr = [];
for (var i=0; i<firstArr.length; i++)
    for (var j=0; j<secondArr.length; j++)
        thirdArr.push(firstArr[i]+secondArr[j]);

var myThirdVariable = thirdArr.join(",");
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
1

You can use the plain old string split method to get 2 arrays. http://www.w3schools.com/jsref/jsref_split.asp

You could then use nested for loops to push the new strings into your 3rd array and then use the join method to create the final string. http://www.w3schools.com/jsref/jsref_join.asp

ScottGuymer
  • 1,885
  • 1
  • 17
  • 22
0

Try

var myFirstVariable = 'green,blue'
var mySecondVariable = 'circle,triangle'

var myThirdVariable = fn(myFirstVariable, mySecondVariable);
console.log(myThirdVariable)

function fn(fv, sv){
    var fa = fv.split(','), sa = sv.split(','), ta = [];
    for(var i = 0; i < fa.length; i++){
        for(var j = 0; j < sa.length; j++){
            ta.push(fa[i] + sa[j])
        }
    }
    return ta.join(',')
}

Demo: Fiddle

Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
0

OK so you don't need jquery to achieve this, just JavaScript.

check out this answer here to help you:

How to merge two arrays in Javascript and de-duplicate items

Community
  • 1
  • 1
Richard
  • 21,728
  • 13
  • 62
  • 101