0

let's assume I have two lists. One existing with some names and a new one with maybe some new names, deleted names or still the same names.

var currentList = ['Daniel', 'Lara', 'Horst'];
var newList = ['Mario', 'Lara'];

// Expected result
toDelete = ['Daniel', 'Horst']; 
toAdd = ['Mario']; 

At the end I need two arrays which contains the new names and those which can be deleted. The names which appear in both array can be ignored.

I don't really know what to call this type of "sorting", so even a buzzword could help. Notice I don't have jQuery at all.

Thanks in advance.

YeppThat'sMe
  • 1,812
  • 6
  • 29
  • 45
  • 2
    If you don't have limitation on third party libraries, take a look at http://underscorejs.org/. It's a must-know for these kind of things. In particular _.intersection(), _.difference() – SDekov Jul 07 '15 at 14:54
  • Change your initial data types to objects, which store internally as hashtables. This can improve your performance from O(n^2) to O(n). – bcorso Jul 07 '15 at 15:17

2 Answers2

2

Thats pretty straightforward, you could do it with 2 loops:

var currentList = ['Daniel', 'Lara', 'Horst'];
var newList = ['Mario', 'Lara'];

var toDelete = [];
var toAdd = [];
for(var i=0;i<newList.length;i++){
    if(currentList.indexOf(newList[i]) >-1)
        toAdd.push(newList[i])
}

for(var i=0;i<currentList.length;i++){
   if(newList.indexOf(currentList[i]) == -1)
       toDelete.push(currentList[i]);
}

console.log('dele',toDelete);
console.log('add',toAdd);

Live example: http://jsfiddle.net/r6L7LpeL/

Jamiec
  • 133,658
  • 13
  • 134
  • 193
-1

First create a third array which is intersection of the current and new list. Second, remove this array from each of the arrays.

Pseudo code:

var intersection_list = intersection(currentList, newList)
var toDelete = currentList - intersectionList;
var toAdd = newList - intersectionList;

You can use the mentioned above library for _.intersection() and _.difference()

Igal S.
  • 13,146
  • 5
  • 30
  • 48