Skip to content
This repository was archived by the owner on May 30, 2019. It is now read-only.

Commit ca30eb3

Browse files
committed
Added a more verbose solution to flatten
1 parent 50e0d9f commit ca30eb3

File tree

1 file changed

+28
-20
lines changed

1 file changed

+28
-20
lines changed

src/arrays.js

Lines changed: 28 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -15,21 +15,25 @@ const reduce = (elements, cb, memo) => {
1515
// Combine all elements into a single value going from left to right.
1616
// Elements will be passed one by one into `cb`.
1717
// `memo` is the starting value. If `memo` is undefined then make `elements[0]` the initial value.
18+
1819
// TODO come back to later
19-
if (!memo) memo = elements.shift();
20-
for (let i = 0; i < elements.length; i++) {
21-
memo += elements[i];
22-
}
23-
return memo;
20+
if (memo) memo = elements.shift();
21+
elements.forEach((value) => {
22+
return cb(memo + value);
23+
});
2424
};
2525

2626
const find = (elements, cb) => {
2727
// Look through each value in `elements` and pass each element to `cb`.
2828
// If `cb` returns `true` then return that element.
2929
// Return `undefined` if no elements pass the truth test.
30-
for (let i = 0; i < elements.length; i++) {
31-
if (cb(elements[i])) return elements[i];
32-
}
30+
31+
// TODO come back to later.
32+
elements.forEach((value, i) => {
33+
if (cb(value)) {
34+
return value;
35+
}
36+
});
3337
return 'undefined';
3438
};
3539

@@ -48,18 +52,22 @@ const filter = (elements, cb) => {
4852
const flatten = (elements) => {
4953
// Flattens a nested array (the nesting can be to any depth).
5054
// Example: flatten([1, [2], [3, [[4]]]]); => [1, 2, 3, 4];
51-
// let nArr = [];
52-
// elements.forEach((value, i) => {
53-
// if (Array.isArray(this[i])) {
54-
// nArr = nArr.concat(this[i].flatten());
55-
// } else {
56-
// nArr.push(this[i]);
57-
// }
58-
// });
59-
// return nArr;
60-
return elements.reduce((flat, toFlatten) => {
61-
return flat.concat(Array.isArray(toFlatten) ? flatten(toFlatten) : toFlatten);
62-
}, []);
55+
56+
// For each value in array,
57+
// If value is an array, recurse into the value array.
58+
const arr = [];
59+
elements.forEach((value) => {
60+
// First make base case.
61+
if (Array.isArray(value)) { // If value is an array.
62+
const nestedArray = flatten(value);
63+
nestedArray.forEach((nestedValue) => {
64+
arr.push(nestedValue);
65+
});
66+
} else { // Else if it's not, just add to new array.
67+
arr.push(value);
68+
}
69+
});
70+
return arr;
6371
};
6472

6573
/* eslint-enable no-unused-vars, max-len */

0 commit comments

Comments
 (0)