Last active
February 18, 2019 15:32
-
-
Save dacanizares/f81e6170bc5db0152fbf3b3561c6ce4c to your computer and use it in GitHub Desktop.
How to Flat nested arrays on Javascript
This file contains 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
"use strict"; | |
/** | |
* Flats an array of arrays | |
* @param {Array} element | |
*/ | |
const Flat = (element) => { | |
if (!Array.isArray(element)) | |
return element | |
return element.reduce((result, curr) => ( | |
result.concat(Flat(curr)) | |
), []) | |
} | |
// Tests for Flat function | |
describe('Flat for int tests', function () { | |
it('can flat an empty array', function () { | |
const input = [] | |
const result = Flat(input) | |
expect(result).toEqual([]) | |
}); | |
it('can flat an array', function () { | |
const input = [1] | |
const result = Flat(input) | |
expect(result).toEqual([1]) | |
}); | |
it('can flat an array of arrays', function () { | |
const input = [1, 2, 3, [4, 5]]; | |
const result = Flat(input); | |
expect(result).toEqual([1, 2, 3, 4, 5]) | |
}); | |
it('can flat an array of arrays of arrays', function () { | |
const input = [1, 2, 3, [4, 5], [6, [7, 8], 9]] | |
const result = Flat(input) | |
expect(result).toEqual([1, 2, 3, 4, 5, 6, 7, 8, 9]) | |
}); | |
}); | |
describe('Flat for string tests', function () { | |
it('can flat an array', function () { | |
const input = ['string'] | |
const result = Flat(input) | |
expect(result).toEqual(['string']) | |
}); | |
it('can flat an array of arrays', function () { | |
const input = ['hello', ['im', 'flat']] | |
const result = Flat(input) | |
expect(result).toEqual(['hello', 'im', 'flat']) | |
}); | |
it('can flat an array of arrays of arrays', function () { | |
const input = ['hello', ['im', ['flat']]] | |
const result = Flat(input) | |
expect(result).toEqual(['hello', 'im', 'flat']) | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment