Reputation: 3117
I´m using Angular2 and I have an array with Date-Objects (~1000). Most of the Date-Objects have got the exactly same dates (for example 2016_11_02; Dates have no hours & minutes). Normally there should be about ~10-20 different Dates in the Array.
Now i want to filter this array and delete the duplicate Dates. So in the end there should be about ~10-20 Date-Objects in the array.
Here´s the code i tried:
let uniqueArray = duplicatesArray.filter(function(elem, pos) {
return channelEPGDates.indexOf(elem) == pos;
});
console.log('unique: ' + uniqueArray.length);
I know this is not correct, cause the unique-Array has the same length as the old array. But how can i compare the Dates itself in the filter-function?
Thanks so much!
Upvotes: 3
Views: 10403
Reputation: 386600
You could use Set
and the spread syntax ...
for it.
unique = src => [...new Set(src)];
var unique = src => [...new Set(src)];
array = ["Mike", "Matt", "Nancy", "Adam", "Jenny", "Nancy", "Carl"];
console.log(unique(array));
To get objects with unique dates, you could filter the data by using a closure over a Set
and a callback for getting the part which has to be unique.
var unique = (src, fn) => src.filter((s => o => !s.has(fn(o)) && s.add(fn(o)))(new Set));
array = [{ date: new Date('2019-11-01')}, { date: new Date('2019-11-01')}, { date: new Date('2019-11-01')}, { date: new Date('2019-11-02')}, { date: new Date('2019-11-01')}, { date: new Date('2019-11-05')}, { date: new Date('2019-11-05')}, { date: new Date('2019-11-04')}, { date: new Date('2019-11-07')}];
console.log(unique(array, ({ date }) => date.toISOString().slice(0, 10)));
.as-console-wrapper { max-height: 100% !important; top: 0; }
Upvotes: 3
Reputation: 6366
Here is a method using the built-in methods on Array.
var arr = ["John", "Jimmy", "John"];
var dArr = []; //Date array
while (dArr.length < 10000) { //Load a lot of pseudo dates
dArr.push(
new Date().getTime() + Math.round(Math.random() * 10)
);
}
function arrayUnique(arr) {
return arr.reduce(function(previousValue, currentValue) {
if (previousValue.some(function(value, index) {
return value === currentValue;
}) === false) {
previousValue.push(currentValue);
}
return previousValue;
}, []);
}
console.log(arrayUnique(arr));
console.log(arrayUnique(dArr).sort());
Upvotes: -1
Reputation: 5126
I would map the dates to epoch time using the getTime
method, and then map them back to Date
objects.
let uniqueArray = duplicatesArray
.map(function (date) { return date.getTime() })
.filter(function (date, i, array) {
return array.indexOf(date) === i;
})
.map(function (time) { return new Date(time); });
Upvotes: 13
Reputation: 556
You can do with jQuery like this :
var names = ["Mike","Matt","Nancy","Adam","Jenny","Nancy","Carl"];
var uniqueNames = [];
$.each(names, function(i, el){
if($.inArray(el, uniqueNames) === -1) uniqueNames.push(el);
});
Upvotes: 0