0

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

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

array2 = ["vanilla", "chocolate", "strawberry"];
2
  • 3
    What do you mean by similar, and from which array are you deleting? Both? Note that you don't have any exact matches in the current arrays, so I'm wondering how you're defining similar. Commented Nov 18, 2010 at 21:33
  • Oops, spelling error. array1 is the original so delete matching strings from array2. Commented Nov 18, 2010 at 21:45

2 Answers 2

2

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;
}
Sign up to request clarification or add additional context in comments.

Comments

0

Array intersect

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

1 Comment

An intersection of the above arrays would return ["apple", "cherry", "strawberry"]. What he wants is (A ∪ B) - (A ∩ B)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.