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'
Advertisement
Answer
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'