diff --git a/src/index.js b/src/index.js index c5f39ded..b3b4420f 100644 --- a/src/index.js +++ b/src/index.js @@ -4,6 +4,7 @@ import snakeToCamel from './snake-to-camel' import padLeft from './pad-left' import randomInteger from './random-integer' import arrayFill from './array-fill' +import sortArray from './sort-array.js' export { flatten, @@ -12,4 +13,5 @@ export { padLeft, randomInteger, arrayFill, + sortArray } diff --git a/src/sort-array.js b/src/sort-array.js new file mode 100644 index 00000000..4c4d6406 --- /dev/null +++ b/src/sort-array.js @@ -0,0 +1,23 @@ +export default sortArray + +/** + * Original Source: http://stackoverflow.com/a/5476833/3316157 + * + * This method will sort an array of values + * + * @param {Array} sortArray - the array to be sorted + * @param {String} dir - the sort direction ("asc" or "desc") + * @return {Array} - the sorted array + */ +function sortArray(sortArray, dir) { + if (dir == "asc") { + sortArray.sort(function(a, b) { + return a.toLowerCase() > b.toLowerCase() + }); + } else { + sortArray.sort(function(a, b) { + return b.toLowerCase() > a.toLowerCase() + }); + } + return sortArray; +} \ No newline at end of file diff --git a/test/sort-array.test.js b/test/sort-array.test.js new file mode 100644 index 00000000..61f7f4b4 --- /dev/null +++ b/test/sort-array.test.js @@ -0,0 +1,16 @@ +import test from 'ava' +import {sortArray} from '../src' + +test('sort an array of strings ascending', t => { + const original = ['apple','orange','peach','banana']; + const expected = ['apple','banana','orange','peach']; + const actual = sortArray(original,'asc') + t.same(actual, expected); +}); + +test('sort an array of strings descending', t => { + const original = ['apple','orange','peach','banana']; + const expected = ['peach','orange','banana','apple']; + const actual = sortArray(original,'desc'); + t.same(actual, expected); +});