How to Get the Length of Longest String in an Array

Finding longest string in array

Available since Javascript 1.8/ECMAScript 5 and available in most older browsers:

var longest = arr.reduce(
function (a, b) {
return a.length > b.length ? a : b;
}
);

Otherwise, a safe alternative:

var longest = arr.sort(
function (a, b) {
return b.length - a.length;
}
)[0];

How to get the length of longest string in an array

try

$maxlen = max(array_map('strlen', $ary));

PHP shortest/longest string length in array

Seems like you should use an array_map()

  // Convert array to an array of string lengths
$lengths = array_map('strlen', $data);

// Show min and max string length
echo "The shortest is " . min($lengths) .
". The longest is " . max($lengths);

Note that the $lengths array is unsorted, so you can easily retrieve the corresponding number for each string length.

Find longest string in array of objects by string property value

You don't need all those checks and nested loops, just map the array to the length of the genre, then take the maximum:

 const longestGenre = Math.max(...array.map(movie => movie.genre.length));

Or dynamically:

const longest = (key, array) => Math.max(...array.map(it => it[key].length));

console.log(longest("genre", /*in*/ array));

PHP Get Longest String in Array without loop

You could sort the strings by length using for example usort and get the first item using reset.

$array = array(
'Google',
'Facebook',
'Twitter',
'Slack',
'Twilio',
);

usort($array, function ($a, $b) {
return strlen($a) < strlen($b);
});

echo reset($array); // Facebook

If there could be more strings with equal length, you could use a foreach and break out of the loop when the length is not equal to the current length of the item to prevent looping the whole list.

$item = reset($array);
$result = [];

if ($item) {
$len = strlen($item);
foreach($array as $value) {
if (strlen($value) === $len) {
$result[] = $value;
continue;
}
break;
}
}

print_r($result);

Result

Array
(
[0] => Facebook
[1] => Test1112
)

Php demo

Get length of longest String in Array

textLengthArray.push($(this)); should be textLengthArray.push($(this).text()); otherwise your array consists of jQuery objects. And indeed jQuerySet has length property. And in your case the set consists of 1 element.

Find longest string in array

You need to check the length of the item and the stored longest string.

if (arr[i].length > longest.length) {
// ^^^^^^^ ^^^^^^^

Just another hint, you could use the first item as start value for longest and start iterating from index 1.

function long_string(arr) {    let longest = arr[0];    for (let i = 1; i < arr.length; i++) {        if (arr[i].length > longest.length) {            longest = arr[i];        }    }    return longest;}
let arr = ["Orebro", "Sundsvall", "Hudriksvall", "Goteborg"];
console.log(long_string(arr));

How do I find the longest strings in the array?

Try this:

func allLongestStrings(inputArray []string) []string {
max := -1 // -1 is guaranteed to be less than length of string
var result []string
for _, s := range inputArray {
if len(s) < max {
// Skip shorter string
continue
}
if len(s) > max {
// Found longer string. Update max and reset result.
max = len(s)
result = result[:0]
}
// Add to result
result = append(result, s)
}
return result
}

As peterSO points out in another answer, the result slice can have a capacity larger than required and can contain string values past the length of slice. The extra allocation and string references may be a problem in some contexts (result is retained for a long time, strings are large, ...). Return a copy of the slice if the allocation and references are a concern.

func allLongestStrings(inputArray []string) []string {
...
return append([]string(nil), result...)
}

If the function can mutate the original slice, then the function result can be constructed in the input slice. This avoids the allocation of the result slice.

func allLongestStrings(inputArray []string) []string {
n := 0
max := -1
for i, s := range inputArray {
if len(s) < max {
// Skip shorter string
continue
}
if len(s) > max {
// Found longer string. Update max and reset result.
max = len(s)
n = 0
}
inputArray[n], inputArray[i] = inputArray[i], inputArray[n]
n++
}
return inputArray[:n]
}

Finding the longest string in an array of Strings

Here.
1. You use j<= animalNames.length;?


  1. You compare animalNames[j + 1]? -> error index out of array

  2. and you return in the first if condition return (animalNames[j]); -> wrong value

Ok, let me make clear.
You find the longest string in an array. You loop over the array then you compare 2 near elements, and then return the bigger one.
With your code, it will return the rabbit. Right?

May be you confuse about the process flow.
There is a simple way.

  1. You assign a variable for the length of the first array element: elementLength = array[0].length; and a value to keep track of the index
  2. You loop over the array
    You check every element with this variable, if bigger then re-assign the element value and update the index.
  3. End of the loop. you have the biggest length and the index

Code:

int index = 0; 
int elementLength = array[0].length();
for(int i=1; i< array.length(); i++) {
if(array[i].length() > elementLength) {
index = i; elementLength = array[i].length();
}
}
return array[index];

that is it.



Related Topics



Leave a reply



Submit