简体   繁体   中英

Javascript - 128_findShortestWordAmongElements — Given an array of different type elements, find the string with the shortest word

I'm doing exercises from Hackreactor and i am currently stuck on this one:

/*
* Notes:
* If there are ties, it should return the first element to appear in the given array.
* Expect the given array to have values other than strings.
* If the given array is empty, it should return an empty string.
* If the given array contains no strings, it should return an empty string.

var output = findShortestWordAmongMixedElements([4, 'two', 2, 'three']);
console.log(output); // --> 'two'

*/

So far, this is what I have:

function findShortestWordAmongMixedElements(arr) {
  // your code here
  var array = [];
  for (var i = 0; i < arr.length; i++) {
    if (typeof arr[i] === 'string') {
      array.push(arr[i]);
      array.sort(function(a,b) {
        return a.length - b.length;
      });
      return array[0];
      } 
    } 
  } 

it returns the word i want, but i am not able to fulfill the failing conditions. What i've tried is, is that i put an if statement after return array[0] that if the type of element that returns is undefined, it returns an empty string. This does not work at all. I also put an if statement for if (arr.length > 0), returning an empty string if the array is empty using ||. This works, but the other one doesn't. Is there a way i can implement these failing conditions in my code?

var min = Math.min.apply(Math, arr.map(function(str) { return str.length; }));

其中“ arr”将是您的数组

The program doesn't work, because it returns the first string it finds:

  for (var i = 0; i < arr.length; i++) { if (typeof arr[i] === 'string') { // ... return array[0]; 

You cannot have a return statement inside the loop, because until you iterate over all the items, you cannot know which item is shortest.

Instead of building a temporary array of strings, sorting, and returning the shortest element, it will be better to track the shortest element as you iterate. Not only it saves memory, the sorting steps makes your implementation inefficient O(n log n) , instead of O(n) .

function findShortestWordAmongMixedElements(arr) {
  var shortest, i, item;
  var minLength = Number.MAX_SAFE_INTEGER;

  for (i = 0; i < arr.length; i++) {
    item = arr[i];
    if (typeof item === 'string') {
      if (item.length < minLength) {
        shortest = item;
        minLength = shortest.length;
      }
    } 
  } 
  return shortest || "";
} 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM