如何在jquery中比较合并两个数组

时间:2011-08-24 05:38:30

标签: jquery arrays

我有两个阵列:

existing_names = username1, username2, username3;

new_names = username1, username4, username5;

我的输出应该是:

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

我怎样才能使用jquery ...

2 个答案:

答案 0 :(得分:0)

使用snook的OC功能,使用纯Javascript非常容易。可以用jQuery做得更短,但总是很有趣:)

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

答案 1 :(得分: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] + ', ');
}