Finding Longest String in 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];

Return longest string in array (JavaScript)

Simply you must change long declaration to :

var long1= '';

and in the for loop condition it should be

arr[i].length > long1.length

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));

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));

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.

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 a 2d array in C

You are only comparing the previous and next strings. You need to check the lengths of all the strings.

void length(char str[][MAX])
{
size_t longest = strlen(str[0]);
szie_t j = 0;

for(size_t i = 1; i < LEN; i++)
{
size_t len = strlen(str[i]);
if(longest < len)
{
longest = len;
j = i;
}
}
printf("%s", str[j]);
}

I am assuming you have at least 1 string and handle corner cases (if user inputs less than LEN strings etc -- depends on how you fill the str with strings).



Related Topics



Leave a reply



Submit