Skip to content

Instantly share code, notes, and snippets.

@psypersky

psypersky/.gitignore

Last active Jun 9, 2016
Embed
What would you like to do?
Flat Array
node_modules
function startFlat(arr) {
let arrRes = []
if (!Array.isArray(arr)) {
return null;
}
return flatArray(arr);
function flatArray(arr) {
for (let i = 0; i < arr.length; i++) {
if (Array.isArray(arr[i])) {
flatArray(arr[i])
} else {
arrRes.push(arr[i]);
}
}
return arrRes;
}
}
module.exports = startFlat;
{
"name": "flat-array",
"version": "1.0.0",
"description": "",
"main": "flatArray.js",
"scripts": {
"test": "mocha"
},
"author": "",
"license": "ISC",
"dependencies": {
"chai": "^3.5.0"
}
}
const chai = require('chai');
const flatArray = require('./flatArray');
describe('Array', function() {
it('Should flat nested arrays', function () {
const arr = [[1, 2], 3];
chai.expect(flatArray(arr)).to.eql([1, 2, 3]);
});
it('Should return null if the input is not an array', function() {
chai.assert.equal(flatArray({ foo: 'bar' }), null);
});
it('Should flat deep nested array', function() {
const arr = [
1,
[
[
2,
3,
4,
[{ five: 'six' }, 'seven'],
8
]
],
9
];
chai.expect(flatArray(arr)).to.eql([1, 2, 3, 4, { five: 'six' }, 'seven', 8, 9]);
})
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.