开发者

Javascript match array

Is there a way to match multiple arrays and delete similar strings.

array1 = ["apple", "cherry", "strawberry"];

array2 = ["van开发者_运维百科illa", "chocolate", "strawberry"];


Your question is not very clear so here are two solutions:

Given ["apple", "cherry", "strawberry"] and ["vanilla", "chocolate", "strawberry"] do you want ["apple", "cherry", "strawberry", "vanilla", "chocolate"]:

function combineWithoutDuplicates(array1, array2) {

   var exists = {};
   var unique = [];

   for(var i = 0; i < array1.length; i++) {
      exists[array1[i]] = true;
      unique.push(array1[i]);
   }

   for(var i = 0; i < array2.length; i++) {
      if(!exists[array2[i]]) {
         unique.push(array2[i]);
      }
   }

   return unique;
}

Or do you want ["vanilla", "chocolate"] (removes duplicates from array2):

function removeDuplicates(array1, array2) {

   var exists = {};
   var withoutDuplicates = [];

   for(var i = 0; i < array1.length; i++) {
      exists[array1[i]] = true;
   }

   for(var i = 0; i < array2.length; i++) {
      if(!exists[array2[i]]) {
         withoutDuplicates.push(array2[i]);
      }
   }

   return withoutDuplicates;
}


Array intersect

http://www.jslab.dk/library/Array.intersect

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜