let printLongestStrings =(array) =>{
let longStr = "";
for(let i = 0; i < array.length; i++){
if(array[i].length >= longStr.length){
longStr += array[i];
}
}
return longStr;
};
console.log(printLongestStrings(["time","ticking","bomb","countup"]));
1) Early returning should be there. You should return longStr at last.
return longStr;
2) You should compare array[i].length with longStr.length not with longStr
array[i].length >= longStr.length
3) You should assign the largest string to longStr. You shouldn't append it in longStr.
longStr = array[i].length >= longStr.length ? array[i] : longStr;
let printLongestStrings = (array) => {
let longStr = "";
for (let i = 0; i < array.length; i++) {
longStr = array[i].length >= longStr.length ? array[i] : longStr;
}
return longStr;
};
console.log(printLongestStrings(["time", "ticking", "bomb", "countup"]));
ALTERNATE SOLUTION: You can achieve the same result using reduce
let printLongestStrings = (array) => {
return array.reduce((acc, curr) => (curr.length >= acc.length ? curr : acc));
};
console.log(printLongestStrings(["time", "ticking", "bomb", "countup"]));
If you want array of largest length string
let printLongestStrings = (array) => {
let map = new Map(),
largestLength = 0;
array.forEach((s) => {
if (s.length >= largestLength) {
largestLength = s.length;
map.has(s.length) ? map.get(s.length).push(s) : map.set(s.length, [s]);
}
});
return [...map.get(largestLength)];
};
console.log(printLongestStrings(["time", "ticking", "bomb", "countup"]));
You're returning before you've checked all the strings
let printLongestStrings = (array) => {
let longStr = "";
for (let i = 0; i < array.length; i++) {
if(array[i].length >= longStr.length)
longStr = array[i];
}
return longStr;
};
console.log(printLongestStrings(["time", "ticking", "bomb", "countup"]));
The above will print the last longest string (ie, if more than 1 input is the longest length it will just output the last)
If yo want all of the strings this length the below would work
let printLongestStrings = (array) => {
let longLen = 0;
let longStr = []
for (let i = 0; i < array.length; i++) {
if(array[i].length == longLen){
longStr.push(array[i])
}
else if(array[i].length > longLen){
longStr = [];
longLen = array[i].length;
longStr.push(array[i])
}
}
return longStr;
};
console.log(printLongestStrings(["time", "ticking", "bomb", "countup"]));
You can make a couple of modifications to your code, and it will work :
longStr when comparing..length is greater.let printLongestStrings = (array) => {
let longStr = "";
for (let i = 0; i < array.length; i++) {
longStr = (array[i].length >= longStr.length) ? array[i] : longStr;
}
return longStr;
};
console.log(printLongestStrings(["time", "ticking", "bomb", "countup"]));