views:

81

answers:

2

Hi, I have the following dynamically generated array:

var myArray = ("0% { left:74px; top:202px; }"   , "44% { left:427px; top:122px; }", "0% { font-size:11px; }", "55% { font-size:49px; }" );

There are 2 entries that have the same start value: 0%. How can I find this and combine it together:

form:
0% { left:74px; top:202px; },
0% { font-size:11px; },
to
0% { left:74px; top:202px; font-size:11px;},

Thank you

Edited the code to a valid array.

+2  A: 

That is an array literal with only one member. You need to end the strings between the commas to separate the members. I would try to rewrite each member as an object literal and use json methods to alternate between string and object. In object form, you can do a mixin to merge the like members.

AutoSponge
+1  A: 

oh, I see.. you're printing your array and this is what you're getting, right?

In that case...

for(var i =0; i< myArray.length ; i++){
  for(var j=i+1; j<myArray.length;j++){
      if(i == j) continue;
      if(myArray[i].substring(0,3) == myArray[j].substring(0,3)){//found matching first 2 chars
         myArray[i] = myArray[i].substring(0,3) + myArray[j].replace(/\{(.*?)\}/,"$1 ;") + myArray[i].substring(4);

        myArray.splice(j--,1);//remove the doup and decrease the counter so you don't skip one now that the array is shorter

      }
  }
}

I didn't test this, but something to this effect :)

Oh.. you edited. What you have now is definitely not an array... but you're closer than you were before.

I think array is a reserved word...

var myArray = ("0% { left:74px; top:202px; }"   , "44% { left:427px; top:122px; }", "etc", "etc" );
Dr.Dredel
Sorry, the code have an error. I can't tell why... I can make my array like this: var myArray = ("0% { left:74px; top:202px; }", "44% { left:427px; top:122px; }", "etc", "etc" );
Mircea
my code might have bugs, but it's what you should do in theory... first make your array look right (as I show at the bottom of my answer). Then loop through the array looking for matches on the first few characters and merge them together and then splice out the duplicate.
Dr.Dredel
Dr.Dredel, the code works now. Sorry for the messed up code.
Mircea