0

How do I remove the oldItems from the newItems string? (remove Blue and Green) newItems is generated from jQuery autocomplete and I would like to remove already selected items from the select list.

newItems = Blue \n Red \n Black \n Yellow \n Green \n
oldItems = Blue,Yellow,Orange,Green

Best regards. Asbjørn Morell.

atmorell
  • 3,052
  • 6
  • 30
  • 44
  • possible duplicate of [JavaScript array difference](http://stackoverflow.com/questions/1187518/javascript-array-difference) – Ejaz May 03 '14 at 12:14
  • Check out this post: http://stackoverflow.com/questions/1187518/javascript-array-difference HTH – Raja Apr 14 '10 at 18:33

1 Answers1

2

One algorithm would be to look at each of the oldItems and search for them in the newItems array. However, if you expect these arrays to reach any length, this is going to be O(n^2). This is essentially the algorithm given by Jacob Relkin.

However, instead, if you sort the two lists, you can do it faster.

var newArray = newItems.split("\n").sort();
var oldArray = oldItems.split(",").sort();
var newUniq = [];

var newLength = newArray.length;
var oldLength = oldArray.length;

var oldI = 0;
var newI = 0;
while (newI < newLength && oldI < oldLength) {
   var oldString = oldArray[oldI].trim();
   var newString = newArray[newI].trim();
   if (oldString == "") {
      oldI++;
   } else if (newString == "") {
      newI++;
   } else if (oldString == newString) {
      /* We only update newI, because if there are multiple copies of the 
       * same string in newItems, we want to ignore them all. */
      newI++;
   } else if (oldString < newString) {
      oldI++;
   } else { /* newArray[newI] < oldArray[oldI] */
      newUniq.push(newArray[newI]);
      newI++;
   }
}
while (newI < newLength) {
   newUniq.push(newArray[newI]);
   newI++;
}

newItems = newUniq.join(" \n ");

This walks through the two lists looking for duplicates in the new list in the old list. This should be O(n log n) because of the two sort operations.

clahey
  • 4,795
  • 3
  • 27
  • 20
  • I am having some difficulty getting your example to work. If I pass in newItems and Old items. The resulting newItems is empty. Before script: var newItems = 'Blue \n Red \n Black \n Yellow \n Green \n' var oldItems = 'Blue,Yellow,Orange,Green' script from above... alert(newItems); //empty - I expected to see Red and Black. Any suggestions? – atmorell Apr 13 '10 at 22:51
  • Can you post your code somewhere? Did you use my code exactly, because I don't know if sort, join, split, or append exist in javascript. I'll rewrite it to be more proper javascript. – clahey Apr 14 '10 at 17:58
  • Thank you. It works now. Had to have the last loop a bit to void a infinity loop: while (newI < newLength) { newUniq.push(newArray[newI]); newI++ } – atmorell Apr 14 '10 at 19:34
  • Yeah, I thought I'd fixed that. Oh well, it's fixed now. – clahey Apr 15 '10 at 05:57