开发者

Javascript Array, find and combine entries with duplicate values

开发者 https://www.devze.com 2023-01-18 01:51 出处:网络
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; }\" );

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.


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.


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" );
0

精彩评论

暂无评论...
验证码 换一张
取 消