Last active
August 29, 2015 14:27
-
-
Save riyadhalnur/cfbbc153408ebdf3a35d to your computer and use it in GitHub Desktop.
Flatten nested arrays to an array one level deep
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var should = require('should'); | |
var flattenArray = require('./flattenArray.js'); | |
describe('Flatten Nested Arrays', function () { | |
it('should flatten a nested array', function () { | |
var testArr = [[1,2,[3]],4]; | |
flattenArray(testArr).should.be.an.Array; | |
flattenArray(testArr).should.equal([1,2,3,4]); | |
}); | |
it('should return a blank array if non-array elements are passed in', function () { | |
var testObj = {hello: 'world'}; | |
flattenArray(testObj).should.equal([]); | |
}); | |
}); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module.exports = function flattenArray (arr, result) { | |
result = result || []; | |
for (var i = 0; i < arr.length; i++) { | |
if (Array.isArray(arr[i])) { | |
flattenArray(arr[i], result); | |
} else { | |
result.push(arr[i]); | |
} | |
} | |
return result; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment