How to find the shortest element in an array with the reduce method

231 views Asked by At

I am not satisfied with my implementation of '.reduce' here. The goal of this problem is to return the length (mind not the word itself!) of the shortest word in an array. As we need to have a value for the first call of the accumulator that is very big to allow .reduce to compare word's length to the accumulator I have used 'Infinity'... Is there a better/more elegant way of using .reduce here? Thanks

    function getLengthOfShortestElement(arr) {

     return arr.reduce(function(acc, element) {
      if (element.length < acc) {
          acc = element.length;
      }
     return acc;
     },Infinity);
     }
2

There are 2 answers

0
Kevin On

I think your solution is just fine. But if using Infinity like this bothers you, you could just set the initial accumulator to zero. Then your first element would be the new accumulator on the first pass.

Example:

function getLengthOfShortestElement(arr) {
  return arr.reduce(function(acc, element, index) {
    if (index == 0) {
        return element.length
    } else {
      if (element.length < acc) {
        acc = element.length;
      }
      return acc;    
    }
  }, 0);
}

const list1 = ['house', 'california', 'ant']
const list2 = ['ant', 'california', 'house']
const list3 = ['', 'a', 'cc']

console.log('running tests')
console.assert(getLengthOfShortestElement(list1) === 3 , 'list1 wrong')
console.assert(getLengthOfShortestElement(list2) === 3 , 'list2 wrong')
console.assert(getLengthOfShortestElement(list3) === 0 , 'list3 wrong')
console.log('done with tests')
0
Dúthomhas On

While @Kevin’s assessment is correct, I find myself dissatisfied with it because it introduces additional logic into each iteration of the loop (the extra if).

Choosing a good initial value is cleaner. You can use Infinity, but you could also just use the length of the first element.

function getLengthOfShortestElement(arr) {
  return arr.reduce(
    function(acc, element) {
      if (element.length < acc) {
        acc = element.length;
      }
      return acc;
    },
    arr.length ? arr[0].length : 0
  );
}

This keeps additional conditional logic at O(1).