Th1
Th1

Reputation: 291

Returning the shortest word

I have an array and I want to return the shortest word in this Array
I tried it with the reduce method
but the code doesn't return the right word, this is my code below, any help would be so appreciated.

const shortestWord = arr => arr
  .reduce((a,_,i,ar) => (ar = ar.filter(i => !Number(i)), a = ar[0], ar[i] < a ? a = ar[i] : '', a), '');

let output = shortestWord([4, 'onee', 'two', 2, 'three', 9, 'four', 'longWord']);
console.log(output); // --> 'two'

Upvotes: 0

Views: 90

Answers (3)

Fullstack Guy
Fullstack Guy

Reputation: 16908

We can filter out the numbers using isNaN and then using reduce compare each word with all the other words. If the current word is smaller than the smallest word we know of, we replace it with the current word:

const shortestWord =
  arr => arr.filter(i => isNaN(i))
  .reduce((a, w, i, ar) => (a = a || ar[0], a = w.length < a.length ? w : a), '');

let output = shortestWord([4, 'onee', 'two', 2, 'three', 9, 'four', 'longWord']);
console.log(output); // --> 'two'

Upvotes: 2

Barmar
Barmar

Reputation: 780724

Filter out numbers before calling reduce(), not inside it. Use typeof to test the type, Number() is for converting from one type to another.

And in the reduce callback function, you need to compare lengths.

const shortestWord = arr => arr
  .filter(el => typeof el == 'string')
  .reduce((a, el) => el.length < a.length ? el : a);

let output = shortestWord([4, 'onee', 'two', 2, 'three', 9, 'four', 'longWord']);
console.log(output); // --> 'two'

Upvotes: 2

Nick
Nick

Reputation: 147146

You can simplify your code by first filtering on whether the value is a number, and then you only need to compare string lengths:

const shortestWord = arr => arr
  .filter(i => i != +i)
  .reduce((a,v) => a.length > v.length ? v : a);

let output = shortestWord([4, 'onee', 'two', 2, 'three', 9, 'four', 'longWord']);
console.log(output); // --> 'two'

Upvotes: 3

Related Questions