0

I have two arrays, Array1 has roughly 500 Date() objects in it. Array2 has about 200 Date() objects. All of these dates are separate instances but Array2 Date() objects will have a matching Date() in Array1.

I need to remove the contents of Array2 from the contents of Array1.

I have considered creating a separate array of unix timestamps from array1 for comparison, but I was hoping there was an easier/more efficient way of doing this.

4
  • Can you use external libraries? Moment for manipulation and Underscore for map, reduce, filter, etc. Can you use libraries like these? Commented Dec 31, 2015 at 21:30
  • I thought map reduce filter are part of ES5, you don't need an external library Commented Dec 31, 2015 at 21:31
  • Browser support is pretty spotty for anything except map, and even that is only supported by IE9 and above. Many / most people still have to support older IE browsers. Commented Dec 31, 2015 at 21:33
  • These are good questions, This is actually being used for a Parse.com backend cloud code module. I don't know enough about it to know if you could import libraries. I know it uses Backbone.js EDIT: It looks like you can use libraries with Parse.com cloud code Commented Dec 31, 2015 at 21:54

1 Answer 1

3

Try a simple filter like this:

var values = Array2.map(function(date) { return date.getTime(); });
var unique = Array1.filter(function(date) { return values.indexof(date.getTime()) == -1 });

If a date in Array1 is also in Array2 (if indexof is not -1) then it will be filtered out. When you are only working with arrays of 200 - 500 dates at a time, efficiency should not be a concern.

Sign up to request clarification or add additional context in comments.

6 Comments

And there's a simple pollyfill available for Array.filter if supporting older browsers.
Note that this will only catch references to the exact same Date objects. If you want to catch dates that have the same value, you will have to actually iterate in a nested loop and compare each date's .getTime(). You could even do so within a certain error tolerance, i.e. dates are equal if they are within a few seconds of each other.
Thanks Jared. Updated answer to use Date.getTime()
Not a problem. Its a good answer: I always like to see array operations. If I ever see another c-style for loop in javascript it'll be too soon.
@AndrewWilliamson Thank you for your answer, i'm going to implement this now and see how it works! Side question: When dealing with javascript and arrays... Say I had an array with 10,000 Date() objects would that be a performance concern? I'm fairly new to javascript.
|

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.