Skip to content

Commit 0c11aee

Browse files
committed
Began implementing sortBy in Underbar. Satisy two of four conditions.
1 parent 30194b4 commit 0c11aee

File tree

1 file changed

+21
-0
lines changed

1 file changed

+21
-0
lines changed

src/underbar.js

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -588,6 +588,27 @@ var _ = {};
588588
// of that string. For example, _.sortBy(people, 'name') should sort
589589
// an array of people by their name.
590590
_.sortBy = function(collection, iterator) {
591+
//apply iterator to collection
592+
593+
if (typeof iterator==='string') {
594+
return collection.sort(function(a, b) {
595+
return (a[iterator]-b[iterator]);
596+
});
597+
} else {
598+
var iterated=[];
599+
var newCollection=[];
600+
_.each(collection, function(val) {
601+
iterated.push([val, iterator(val)]);
602+
});
603+
604+
iterated.sort(function(a, b) {
605+
return a[1]-b[1];
606+
});
607+
_.each(iterated, function(val) {
608+
newCollection.push(val[0]);
609+
});
610+
return newCollection;
611+
}
591612
};
592613

593614
// Zip together two or more arrays with elements of the same index

0 commit comments

Comments
 (0)