To find the longest string in javascript array, we need to loop through all the elements and compare their lengths. The one which has the maximum length is the longest.
Code Example
const longestStringFromArray = (myArr) => { var stringIndex = 0; var stringLength = 0; myArr.forEach((element, index) => { if(typeof element === 'string'){ if(element.length > stringLength){ stringIndex = index; stringLength = element.length; } } else if (typeof element === 'number'){ if((""+element).length > stringLength){ stringIndex = index; stringLength = (""+element).length; } } }); return myArr[stringIndex]; } var myArr = [ 1, 2, 4534, "hello", "world", "Help Animals" ] var longestString = longestStringFromArray(myArr)
Let’s understand this code. We defined a function longestStringFromArray
which accepts one parameter i.e. the input array, myArr
.
You may also like-
Next we are defining two local variables – stringIndex
and stringLength
. Our function works in a way that it loops over all the values of array and checks if the current value is greater than previous values. So, stringIndex
holds the index of element whose value is greater than previous elements. While, stringLength
holds the length of value of element which is maximum till encountered in loop.
This function works on numbers and strings values only. Any other type of data will be ignored. We are using javascript’s typeof
function for type checking.
After running all the values in loop, we will end up getting the index and length of element with longest string in the array.
Live Demo
Similar Articles