Skip to content

Instantly share code, notes, and snippets.



Last active Mar 10, 2020
What would you like to do?
Array Flatten
// Decided against a testing framework for something so simple.
// This test takes an array, loops through each top level index
// and logs an error if the index contains an array.
// Passes are tallied, and passes/fails are output at the end of the test.
const flattenTest = arr => {
// Define error message and initialize pass counter
const errorMessage = ind => `Index ${ind} contains an array`;
let passCount = 0;
arr.forEach((item, ind) => {
// If the item is an array, log the message
// If not an array, increment pass counter
} else {
// Log out results
console.log(`${arr.length} total top level indexes.`);
console.log(`${passCount} tests passed.`);
console.log(`${arr.length - passCount} tests failed.`);
module.exports = flattenTest;
const flatten = arr => {
let outputArr = [];
// Loop through each index of the array
arr.forEach(item => {
// If the current item is not an array, push its value immediately.
// If the current item is an array, recurse into it.
// It's usually better to not use recursion, but in this case,
// depth is unknown, and recursion makes sense.
} else {
// Spread the results of the recursion into the output array.
return outputArr;
// Created for use with Node or other CommonJS
module.exports = flatten;
// Run this file using `node index.js` to see results.
const flattenTest = require('./flatten-test.js');
const flatten = require('./flatten.js');
const arr = [[1,2,[3]],4];
// First, test flatten function
console.log('Running example array with flatten function');
// Second, show test failures using input array
console.log('\nRunning example array without flatten function')
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.