I have the following code, that groups similar todos into an array of arrays, using lodash (https://lodash.com). Here is a plnkr http://plnkr.co/edit/t4J5bKGjMlQxW2z9Zh7x?p=preview (open your console and look into script.js
)
function Todo(value) { this.value = value; this.isSimilar = function(todo) { return this.value == todo.value; }; } var _data = [ new Todo("hello"), new Todo("world"), new Todo("foo"), new Todo("bar"), new Todo("hello") ]; var processedTodos = []; var groups = _.compact(_.map(_data, function(todo) { if(processedTodos.indexOf(todo)>-1) { return; } var similarTodos = _.filter(_data, function(todo2) { return todo!==todo2 && todo.isSimilar(todo2); }); similarTodos.unshift(todo); // prepend todo to front of array [].push.apply(processedTodos, similarTodos); return similarTodos; })); console.log(groups);
groups
contains an array of arrays, where similar todos are in the same array.
For example, when I input this (these are JS objects, but for the sake of readability in JSON):
[ {"value":"hello"}, {"value":"world"}, {"value":"foo"}, {"value":"bar"}, {"value":"hello"} ]
It returns this:
[ [{"value":"hello"},{"value":"hello"}], [{"value":"world"}], [{"value":"foo"}], [{"value":"bar"}] ]
It groups together similar objects.
But the whole code doesn't feel right, there must be a better way to do this!
Another bad thing is that I need an additional array to store the already checked todos (which avoid me duplicate arrays like [todo1,todo2]
and [todo2,todo1]
.
Last but not least, I have to remove undefined
values from the array with _.compact
, because this line returns undefined
when the todo was already processed:
if(processedTodos.indexOf(todo)>-1) { return; }
Any idea how to improve this code?