1

I am having two arrays:

existing_names = username1, username2, username3;

new_names = username1, username4, username5;

My output Should be:

new_names = username1, username2, username3, username4, username5;

How can i able to do this using jquery...

Fero
  • 12,969
  • 46
  • 116
  • 157
  • You can do this with JavaScript... Look at this question http://stackoverflow.com/questions/1584370/how-to-merge-two-arrays-in-javascript – Chuck Norris Aug 24 '11 at 05:43

2 Answers2

0

Use snook's OC function and its fairly easy with pure Javascript. Could possibly be done shorter with jQuery, but always fun to do without :)

DEMO: http://jsfiddle.net/wesbos/MvurR/

var existing_names = ["username1", "username2", "username3"];

var new_names = ["username1", "username4", "username5"];

/* http://snook.ca/archives/javascript/testing_for_a_v */ 

function oc(a)
{
  var o = {};
  for(var i=0;i<a.length;i++)
  {
    o[a[i]]='';
  }
  return o;
}


for (var i=0; i < existing_names.length; i++) {
    if (!(existing_names[i] in oc(new_names))) {
        new_names.push(existing_names[i]);
    }
}

console.log(new_names);
wesbos
  • 25,839
  • 30
  • 106
  • 143
  • 2
    Are you really creating an object of all new_names on every iteration of the loop? That's not very efficient. You really ought to move the oc function call before the loop. – jfriend00 Aug 24 '11 at 06:29
0

http://jsfiddle.net/AYgNW/3/

var existing_names = ['username1','username2','username3'];
var new_names = ['username1','username4','username5'];

function mergeArrays( a1, a2 ) {

    var len1 = a1.length;
    var len2 = a2.length;
    var found = false;

    for ( var x = 0; x < len2; x += 1 ) {

        found = false;

        for ( var y = 0; y < len1; y += 1 ) {
             if ( a1[y] === a2[x] ) {
                found = true;
                break;
            }
        }

        if ( ! found ) {
            a1.push( a2[x] );
        }

    }

    return a1;

}

// merge arrays
new_names = mergeArrays( new_names, existing_names );

// sort the resulting array
new_names.sort();

for ( var x = 0; x < new_names.length; x += 1 ) {
    document.write(new_names[x] + ', ');
}
Jose Faeti
  • 12,126
  • 5
  • 38
  • 52