-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpumpkin_prizes.js
78 lines (63 loc) · 2.3 KB
/
pumpkin_prizes.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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
/*
Scrimba mascot Pumpkin has won the grand prize at an international
cat show. Below are Pumpkin's scores from the judges, as well as all the
prizes he's won. In all the excitement of victory,
they've become a jumbled mess of nested arrays. Let's
help Pumpkin by sorting it out.
Write a function to flatten nested arrays of strings or
numbers into a single array. There's a method
for this, but pratice both doing it manually and using the method.
Example input: [1, [4,5], [4,7,6,4], 3, 5]
Example output: [1, 4, 5, 4, 7, 6, 4, 3, 5]
*/
const kittyScores = [
[39, 99, 76], 89, 98, [87, 56, 90],
[96, 95], 40, 78, 50, [63]
];
const kittyPrizes = [
["💰", "🐟", "🐟"], "🏆", "💐", "💵", ["💵", "🏆"],
["🐟","💐", "💐"], "💵", "💵", ["🐟"], "🐟"
];
// 1ST WAY -->
function flatten(arr){
// arr = arr.toString().split("").filter((item) => {
// return item.trim() != ",";
// })
// console.log(arr); // only works for kittyScores
// return arr.flat() ; // flattens upto depth 1 & does not support all browsers and engines
return [...arr.flat(Infinity)]; // flatens to infinity level & supports all browsers and engines
}
console.log(flatten(kittyPrizes));
console.log(flatten(kittyScores));
// 2ND WAY -->
// function flatten(arr){
// initialize a new, empty array
// loop through the passed in array and check - string or array?
// if the item is string, push into the new array
// if the item is an array, loop through it, pushing each item into the array
// return new array
// const newArr = [];
// arr.forEach(element => {
// if(Array.isArray(element)){
// // element.forEach(item => newArr.push(item));
// newArr.push(...flatten(element)); //preferred
// // newArr.push(...element);
// } else {
// newArr.push(element);
// }
// });
// return newArr;
// }
// console.log(flatten(kittyPrizes));
// console.log(flatten(kittyScores));
// 3RD WAY -->
// function flatten(arr) {
// return arr.reduce((flattenedArray, element) => {
// if (Array.isArray(element)) {
// flattenedArray.push(...flatten(element));
// } else {
// flattenedArray.push(element);
// }
// return flattenedArray;
// }, []);
// }