2

What is the most efficient way to compare two javascript arrays and create two new arrays of missing and new elements? Array elements will be always strings or numbers and it is not 100% sure that they will be sorted in any way.

var old_array = ['11', '13', '14', '18', '22', '23', '25'];
var new_array = ['11', '13', '15', '16', '17', '23', '25', '31'];
var missing_elements = [];
var new_elements = [];

/*
* some magic goes here
* which compares
* new_array with old_array
*/

console.log(missing_elements); // would produce ['14', '18', '22']
console.log(new_elements); // would produce ['15', '16', '17', '31']

Thanks a bunch!

0

3 Answers 3

3

The code to Drew Noakes' solution:

var old_array = ['11', '13', '14', '18', '22', '23', '25'];
var new_array = ['11', '13', '15', '16', '17', '23', '25', '31'];
var missing_elements = _.difference(old_array, new_array);
var new_elements = _.difference(new_array, old_array);

console.log(missing_elements); // would produce ['14', '18', '22']
console.log(new_elements); // would produce ['15', '16', '17', '31']
Sign up to request clarification or add additional context in comments.

Comments

2

I would use Underscore.js's intersection and difference functions.

3 Comments

Thanks for this tip, +1 to you, but I accepted Lukas' answer just because he added a code snippet.
The main thing is that you found a solution that works for you.
Also, you asked for the most efficient way. Mine's probably the simplest, but Bergi's may actually be more efficient. Perhaps someone could test this with jsperf.com
0

Sorting will be the most efficient (assuming you don't have any other preconditions to base an optimization on):

var old_array_sorted = old_array.slice().sort(); // slicing for not mutating
var new_array_sorted = new_array.slice().sort(); // the original array

for (var o=0, n=0; o<old_array_sorted.length && n<new_array_sorted.length; ) {
    if (old_array_sorted[o] < new_array_sorted[n])
        missing_elements.push ( old_array_sorted[o++] );
    else if (old_array_sorted[o] > new_array_sorted[n])
        new_elements.push( new_array_sorted[n++] );
    else
        n++, o++;
}
[].push.apply(missing_elements, old_array_sorted.slice(o));
[].push.apply(new_elements, new_array_sorted.slice(n));

Comments

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.