diff --git a/test/arrays.js b/test/arrays.js index 80da71f6f..c648f081b 100644 --- a/test/arrays.js +++ b/test/arrays.js @@ -50,10 +50,13 @@ $(document).ready(function() { }); test("arrays: flatten", function() { - var list = [1, [2], [3, [[[4]]]]]; - equals(_.flatten(list).join(', '), '1, 2, 3, 4', 'can flatten nested arrays'); - var result = (function(){ return _.flatten(arguments); })(1, [2], [3, [[[4]]]]); - equals(result.join(', '), '1, 2, 3, 4', 'works on an arguments object'); + if (window.JSON) { + var list = [1, [2], [3, [[[4]]]]]; + equals(JSON.stringify(_.flatten(list)), '[1,2,3,4]', 'can flatten nested arrays'); + equals(JSON.stringify(_.flatten(list, true)), '[1,2,3,[[[4]]]]', 'can shallowly flatten nested arrays'); + var result = (function(){ return _.flatten(arguments); })(1, [2], [3, [[[4]]]]); + equals(JSON.stringify(result), '[1,2,3,4]', 'works on an arguments object'); + } }); test("arrays: without", function() { @@ -97,6 +100,9 @@ $(document).ready(function() { test("arrays: union", function() { var result = _.union([1, 2, 3], [2, 30, 1], [1, 40]); equals(result.join(' '), '1 2 3 30 40', 'takes the union of a list of arrays'); + + var result = _.union([1, 2, 3], [2, 30, 1], [1, 40, [1]]); + equals(result.join(' '), '1 2 3 30 40 1', 'takes the union of a list of nested arrays'); }); test("arrays: difference", function() { diff --git a/underscore.js b/underscore.js index f2c8c94b7..f2f42898f 100644 --- a/underscore.js +++ b/underscore.js @@ -345,9 +345,9 @@ }; // Return a completely flattened version of an array. - _.flatten = function(array) { + _.flatten = function(array, shallow) { return _.reduce(array, function(memo, value) { - if (_.isArray(value)) return memo.concat(_.flatten(value)); + if (_.isArray(value)) return memo.concat(shallow ? value : _.flatten(value)); memo[memo.length] = value; return memo; }, []); @@ -377,7 +377,7 @@ // Produce an array that contains the union: each distinct element from all of // the passed-in arrays. _.union = function() { - return _.uniq(_.flatten(arguments)); + return _.uniq(_.flatten(arguments, true)); }; // Produce an array that contains every item shared between all the