Nick H
Nick H

Reputation: 8992

Javascript - Remove Array of Date() objects from another array of Date() objects

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.

Upvotes: 0

Views: 1102

Answers (1)

Andrew Williamson
Andrew Williamson

Reputation: 8696

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.

Upvotes: 3

Related Questions