javascript - In array find match and replace it by jQuery -


here have array set:

totalarray =[              [1,2,3,4],              [8,9,10],                   [15,16,17],              [8,14,20]             ] 

and need make combine if set have same number.

like that:

totalarray =[              [1,2,3,4],              [8,9,10,14,20],              [15,16,17]             ] 

other example:

totalarray =[ [1,2,3,4], [6,10,19], [6,16,4], [4,14,20] ] 

to

totalarray =[ [1,2,3,4,6,10,14,16,19,20] ] 

so, need make if number match on other array , make together. e.g:

array = [[1,2,3,4],[8,9,10],[8,11,12]];  

array[1][0] , array[2][0] match, array become array = [1,2,3,4],[8,9,10,11,12].

any suggestion?

you have write boring looping code. might make little more manageable with

  • [].push.apply(arr1, arr2); : pushes elements of arr2 arr1 without building new array
  • indexof : looks element in array. if want support ie8, tagged question , may use $.inarray

here's code :

var totalarray =[   [1,2,3,4],   [8,9,10],        [15,16,17],   [8,14,20] ]; var result = [totalarray[0]]; function prec(tai) {   (var j=0; j<result.length; j++) {     (var k=0; k<tai.length; k++) {       if (result[j].indexof(tai[k])!=-1) {         return result[j];       }     }   }   return null; } (var i=1; i<totalarray.length; i++) {   var arr = prec(totalarray[i]);   if (arr) [].push.apply(arr, totalarray[i]);   else result.push(totalarray[i]); } 

result array want.

demonstration


Comments

Popular posts from this blog

css - Which browser returns the correct result for getBoundingClientRect of an SVG element? -

gcc - Calling fftR4() in c from assembly -

.htaccess - Matching full URL in RewriteCond -