-
Notifications
You must be signed in to change notification settings - Fork 0
/
flatten.js
44 lines (36 loc) · 1.06 KB
/
flatten.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
//eqArrays function
const eqArrays = function(Array1, Array2) {
if (Array.isArray(Array1) &&
Array.isArray(Array2)) {
for (const [i, value] of Array1.entries()) {
const value2 = Array2[i];
if (value !== value2) {
return false;
}
}
} return true;
};
//assertArraysEqual function
const assertArraysEqual = function(Array1, Array2) {
if (eqArrays(Array1, Array2)) {
console.log(`Assertion Passed: ${Array1} ✅✅✅ ${Array2}`);
} else {
console.log(`Assertion Failed: ${Array1} 🛑🛑🛑 ${Array2}`);
}
};
// Create a function flatten which will take in an array containing elements including nested arrays of elements, and return a "flattened" version of the array.
const flatten = function(arr) {
let newArr = [];
for (let i = 0; i < arr.length; i++) {
if (Array.isArray(arr[i])) {
for (let j = 0; j < arr[i].length; j++) {
newArr.push(arr[i][j]);
}
} else {
newArr.push(arr[i]);
}
}
return newArr;
};
module.exports = flatten;
console.log(flatten([1, 2, [3, 4], 5, [6]]));