I am generating an array of calendar events and then (using code I got from user 'Cooper') I am deduplicating the list to create a new array: dedList
// This code creates a deduplicated array (dedList) from my array 'events' (parts of this code are from Cooper on StackOverflow... and I don't really understand it all)
var dedList=[];
var obj={eA:[]};
for(var i=0;i<events.length;i++) {
var key=events[i].getTitle() + events[i].getDescription();
if(!obj.hasOwnProperty(key)) {
obj[key]={
title: events[i].getTitle(),
description: events[i].getDescription(),
guest_list: events[i].getGuestList(),
guests: events[i].getGuestList().length,
start: events[i].getStartTime(),
end: events[i].getEndTime(),
recurs: events[i].isRecurringEvent(),
duration: "",
creator: events[i].getCreators(),
color: events[i].getColor() ,
copies: 0,
category: "",
};
obj.eA.push(key);
}else{
obj[key].copies+=1; //count the copies
}
}
for(var i=0;i<obj.eA.length;i++) {
dedList.push(obj[obj.eA[i]]);
}
This is working perfectly, but I'm using some well shared code to sort dedList by "category" and it's generating error I've never seen before: "Comparison method violates its general contract." Here's the line causing the error, followed by the function I am using:
dedList.sort(dynamicSort("category")); // this line generates the error
function dynamicSort(property) {
var sortOrder = 1;
if(property[0] === "-") {
sortOrder = -1;
property = property.substr(1);
}
return function (a,b) {
var result = (a[property] < b[property]) ? -1 : (a[property] > b[property]) ? 1 : 0;
return result * sortOrder;
}
}
Any suggestions? I'm pretty new to google scripting so I don't completely understand how the dynamicSort function works, and that is making it hard for me to debug the error. Thanks!
MCVE:
function sortTest() {
var arr = [];
for (i = 0; i < 50; ++i) {
arr.push({ a: '' }, {}, { a: {} });
}
Logger.log(arr.sort(dynamicSort('a')));
}
function dynamicSort(property) {
var sortOrder = 1;
return function (a,b) {
var result = (a[property] < b[property]) ? -1 : (a[property] > b[property]) ? 1 : 0;
return result * sortOrder;
}
}
- Engine: Rhino (Old)
- Error:
Comparison method violates its general contract