sopstem2428
sopstem2428

Reputation: 11

Determine if one of the elements in an array is a string

Given an array of mixed types, "getLongestWordOfMixedElements" returns the longest string in the given array.

Notes:

How do I find out if the array contains a string or not, as in this code:

function getLongestWordOfMixedElements(arr) {

    if (arr.length === 0) return ""
    var max = 0
    for (var i = 0; i < arr.length; i++){
        if(arr[i].length > max) max = arr[i]
    }
    return max
}

getLongestWordOfMixedElements([3, 'word', 5, 'up', 3, 1]);

Upvotes: 0

Views: 645

Answers (3)

Stefan Rein
Stefan Rein

Reputation: 9062

You iterate over the element and check if its type is a string. You can do so with typeof.

Let us say you would've a bunch of data and would not like to double your memory usage / or for the sake of the example in your code:

function getLongestWordOfMixedElements(arr) {
    var max = "";

    if (arr.length) {
        arr.forEach(function (item) {
            if (typeof item === "string" && item.length > max) {
                max = item;
            }
        });
    }

    return max;
}


console.log(getLongestWordOfMixedElements([3, 'word', 5, 'up', 3, 1, {foo:4}]));

In your code you would change it this way:

for (var i = 0; i < arr.length; i++) {
    var item = arr[i];

    if (typeof item === "string" && item.length > max) {
        max = arr[i];
    }
}

Upvotes: 0

Bruce Smith
Bruce Smith

Reputation: 811

Well here's my version of it...

function getLongestWordOfMixedElements(arr) {
  let result = '';

  if (arr.length) {
    for(i in arr) {
      const value = arr[i];

      if (value && typeof value === 'string' && value.length > result.length) {
        result = value;
      }
    }
  }

  return result;
}


getLongestWordOfMixedElements([333333, 'word', 5, 'up', 3, 1]);

Upvotes: 0

Phil
Phil

Reputation: 164794

You can filter the array for strings then use a reduce operation to find the longest one

function getLongestWordOfMixedElements(arr) {
  return arr
    .filter(item => typeof item === 'string')
    .reduce((longest, str) => str.length > longest.length ? str : longest, '');
}

console.log(getLongestWordOfMixedElements([3, 'word', 5, 'up', 3, 1]));


Note that if any words are the same length, the earlier one in the array is returned.


Additionally, you could skip the filter and do the type check in the reduce...

return arr.reduce((longest, str) => {
  return typeof str === 'string' && str.length > longest.length ?
    str : longest;
}, '')

Upvotes: 4

Related Questions