Alex
Alex

Reputation: 153

Javascript match array

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

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

array2 = ["vanilla", "chocolate", "strawberry"];

Upvotes: 0

Views: 1635

Answers (2)

zod
zod

Reputation: 12417

Array intersect

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

Upvotes: 0

Vivin Paliath
Vivin Paliath

Reputation: 95508

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

Upvotes: 2

Related Questions