I need to get the array element which has maximum length in the given array.
Suppose there is an array:
const a = ["apple","banana","mango","watermelon","grapes"];
Here I need to get watermelon as output because watermelon has the maximum length.
Below is what has been tried
let length7=0;
let maxlength = function fn() {
for (i7=0; i7<a.length; i7++) {
if (a[i7].length > length7) {
length7=a[i7].length
}
};
return length7;
};
console.log(maxlength())
From this I am getting the length of the maximum string(as 10). But I need to get the output as watermelon.
Please explain an optimal solution to the problem.
You could store the longest element in a seperate variable and return that.
let maxlength = function fn() {
let length7 = 0;
let value = "";
for (i7 = 0; i7 < a.length; i7++) {
if (a[i7].length > length7) {
length7 = a[i7].length;
value = a[i7];
}
}
return value;
}
The below solution may be one possible solution to achieve the desired objective.
Code Snippet
const getLongestWordIn = arr => (
arr.reduce(
(acc, word) => (word.length > acc.length ? word : acc),
""
)
);
const a = ["apple","banana","mango","watermelon","grapes"];
console.log(getLongestWordIn(a));
Explanation
.reduce to iterate over the arrayacc is initialized as empty string ""acc, then assign that word to accaccYou need to store either (1) just the element with the maximum length or (2) both the element and it's maximum length. You should also move the current max variable (max7 in your case) inside the function. Putting this together and opting for (2):
function longestElement(arr) {
if (!arr.length) return; // empty array
let longest = arr[0];
for (let i = 1; i < arr.length; i++)
longest = arr[i].length > longest.length ? arr[i] : longest;
return longest;
}
let a=["apple","banana","mango","watermelon","grapes"];
console.log(longestElement(a)); // "watermelon"
If you want to shorten this, you can use reduce:
const longestElement = (arr) => arr.reduce((x, y) => x.length > y.length ? x : y);