Skip to content

Instantly share code, notes, and snippets.

@timbuckley
Last active April 5, 2016 16:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save timbuckley/6c77c67f77cb1b9c8c0c68e87fb453e6 to your computer and use it in GitHub Desktop.
Save timbuckley/6c77c67f77cb1b9c8c0c68e87fb453e6 to your computer and use it in GitHub Desktop.
(defn flatten [nested]
(reduce
(fn [acc el]
(concat acc (if (sequential? el)
(flatten el)
[el])))
[]
nested))
(flatten [1 2 [3] [4 5] [[6 7] 8]])
// === Current JavaScript (ES5) syntax, using simple forEach ===
function isList(x) {
return Array.isArray(x)
}
function flatten(nested) {
var newArray = [];
nested.forEach(function(item) {
if (isList(item)) {
newArray = newArray.concat(flatten(item));
} else {
newArray.push(item);
}
})
return newArray;
}
var nested = [0,[1,2],[[3], 4], 5, 6]
flatten(nested)
// === ES6 syntax, + using reduce ===
const isList = x => Array.isArray(x)
const flatReducer = (acc, i) => acc.concat(isList(i) ? flatten(i) : [i])
const flatten = (nested) => nested.reduce(flatReducer, [])
// Reduce is a useful method that iterables (like arrays) have that let's you build
// something new by doing something with each element of the iterable at a time.
// It takes a function and an optional starting point (e.g. an empty list).
// The function you pass (aka the "reducer") takes two arguments: the thing you're
// building (aka accumulator), and the current element in the array/iterable.
// It should return the next value of the accumulator.
// (acc, i) => acc.concat(isList(i) ? flatten(i) : [i])
// The reducing function here ^ returns the accumulator concated with the next
// element in the array. If the element is itself a list, we recursively call flatten
// on the element to make sure it's flat before continuing on.
# Flattening a nested list. Helper method is not strictly necessary
def is_list(x):
return type(x) == list
def flatten(nested):
"""Flatten an arbitrarily nested list"""
new_list = []
for item in nested:
if is_list(item):
new_list.extend(flatten(item)) # recursion
else:
new_list.append(item)
return new_list
nested = [0,[1,2],[[3]], 4, 5]
flatten(nested)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment