{"record":{"id":"1e27622d34312c0a","repo":"jashkenas/backbone","slug":"cannot-sort-a-set-without-a-comparator","errorCode":null,"errorMessage":"Cannot sort a set without a comparator","messagePattern":"Cannot sort a set without a comparator","errorType":"exception","errorClass":"Error","httpStatus":null,"severity":"error","filePath":"backbone.js","lineNumber":1045,"sourceCode":"\n    // Return models with matching attributes. Useful for simple cases of\n    // `filter`.\n    where: function(attrs, first) {\n      return this[first ? 'find' : 'filter'](attrs);\n    },\n\n    // Return the first model with matching attributes. Useful for simple cases\n    // of `find`.\n    findWhere: function(attrs) {\n      return this.where(attrs, true);\n    },\n\n    // Force the collection to re-sort itself. You don't need to call this under\n    // normal circumstances, as the set will maintain sort order as each item\n    // is added.\n    sort: function(options) {\n      var comparator = this.comparator;\n      if (!comparator) throw new Error('Cannot sort a set without a comparator');\n      options || (options = {});\n\n      var length = comparator.length;\n      if (_.isFunction(comparator)) comparator = comparator.bind(this);\n\n      // Run sort based on type of `comparator`.\n      if (length === 1 || _.isString(comparator)) {\n        this.models = this.sortBy(comparator);\n      } else {\n        this.models.sort(comparator);\n      }\n      if (!options.silent) this.trigger('sort', this, options);\n      return this;\n    },\n\n    // Pluck an attribute from each model in the collection.\n    pluck: function(attr) {\n      return this.map(attr + '');","sourceCodeStart":1027,"sourceCodeEnd":1063,"githubUrl":"https://github.com/jashkenas/backbone/blob/f229c75b194a63a8e07a3313ce43e8d2dc105327/backbone.js#L1027-L1063","documentation":"Backbone's Collection.sort() requires the collection to have a comparator, which defines the ordering of models. If this.comparator is falsy, Backbone deliberately throws this error instead of silently leaving the collection unsorted. The comparator can be a function or a string naming an attribute to sort by.","triggerScenarios":"Calling collection.sort() on a Collection instance whose constructor options, 'comparator' property, or set() call never defined a comparator; also triggered internally by add/fetch with {sort:true} options on a comparator-less collection.","commonSituations":"Defining a comparator on the wrong object (e.g., on a plain object instead of the Collection class or prototype); building collections dynamically without a comparator then calling sort(); upgrading Backbone and relying on a comparator set via attributes rather than as a class property; copying collection code and omitting the comparator.","solutions":["Define a comparator on the collection: 'comparator: \"name\"' (sort by attribute) or 'comparator: function(m){ return m.get(\"name\"); }'.","Pass a comparator at construction: new Backbone.Collection(models, {comparator: 'id'}).","Use a string comparator naming a model attribute if a custom function isn't needed.","Before sorting, guard: if (!collection.comparator) collection.comparator = 'name'; then call collection.sort().","If ordering doesn't matter, remove the sort() call instead of sorting a comparator-less collection."],"exampleFix":"// before\nvar c = new Backbone.Collection(models);\nc.sort(); // throws: Cannot sort a set without a comparator\n\n// after\nvar c = new Backbone.Collection(models, {comparator: 'name'});\nc.sort(); // works","handlingStrategy":"validation","validationCode":"function canSort(collection) {\n  return typeof collection === 'object' && collection != null &&\n    (typeof collection.comparator === 'function' || typeof collection.comparator === 'string');\n}\nif (!canSort(myCollection)) myCollection.comparator = 'name';\nmyCollection.sort();","typeGuard":"function hasComparator(c) {\n  return c instanceof Backbone.Collection &&\n    (typeof c.comparator === 'function' || typeof c.comparator === 'string');\n}","tryCatchPattern":"try {\n  collection.sort();\n} catch (e) {\n  if (e.message === 'Cannot sort a set without a comparator') {\n    collection.comparator = 'name';\n    collection.sort();\n  } else { throw e; }\n}","preventionTips":["Always declare comparator as a property of the Collection definition, not set ad hoc.","Prefer string comparators ('attrName') when a simple attribute sort suffices.","Add a unit test that sorts every collection used in the app.","When constructing collections dynamically, pass {comparator: ...} in options.","Never rely on add()/fetch() to maintain order without a comparator present."],"tags":["backbone","collection","comparator","sorting"],"backgroundTag":"missing-comparator","analyzedSha":"f229c75b194a63a8e07a3313ce43e8d2dc105327","analyzedAt":"2026-08-28T23:02:54.813Z","schemaVersion":2},"datasetVersion":"2026-08-29T02:17:18.158Z"}