Last active
December 13, 2023 15:27
-
-
Save ronaldroe/8ac6ad5861e7650e52a27a04aa705ef8 to your computer and use it in GitHub Desktop.
Array Flatten
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
// 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(Array.isArray(item)){ | |
console.error(errorMessage(ind)); | |
// If not an array, increment pass counter | |
} else { | |
passCount++; | |
} | |
}); | |
// 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; |
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
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(!Array.isArray(item)){ | |
outputArr.push(item); | |
// 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. | |
outputArr.push(...flatten(item)); | |
} | |
}); | |
return outputArr; | |
} | |
// Created for use with Node or other CommonJS | |
module.exports = flatten; |
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
// 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'); | |
flattenTest(flatten(arr)); | |
// Second, show test failures using input array | |
console.log('\nRunning example array without flatten function') | |
flattenTest(arr); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment