-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathlongestSubStringNestedArray.js
47 lines (38 loc) · 1.2 KB
/
longestSubStringNestedArray.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
// helper function
function isArray(value) {
return value && typeof value === "object" && value.constructor === Array
}
function isString(value) {
return typeof value === 'string' || value instanceof String;
}
// using simple for loop
function longestString(arr) {
var largestStr = "";
for (var i = 0; i < arr.length; i++) {
var currentStr;
if (isArray(arr[i])) {
currentStr = longestString(arr[i]);
} else if (isString(arr[i])) {
currentStr = arr[i];
}
if (currentStr.length > largestStr.length) {
largestStr = currentStr;
}
}
return largestStr;
}
// using reduce function
function longestString(arr) {
return arr.reduce(function(acc, curr) {
var currentStr;
if (isArray(curr)){
currentStr = longestString(curr)
} else {
currentStr = curr;
}
return currentStr.length > acc.length ? currentStr : acc;
}, '')
}
// test case
const stringArray = ["pa", "abd", ["abcd", "derfg", ["asdasd", "DGdgdfsgJHAHAGyqyqu", "gjhsgfjgjhgjhg", "safgjgsjfhagjhgsdfsadfiooioioioioioi"], "llkllklk", "qttwrtr"], "sdafasdf", "jhsajhfjhajshfkuiu", "sadfsafsd"];
console.log(longestString(stringArray) === "safgjgsjfhagjhgsdfsadfiooioioioioioi"); // true;