Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Better way to write this JS reduce() code?

Tags:

javascript

the function below simply returns the smallest element in the given array using a reduce function. However, I quickly realized that the code below would throw a TypeError if the given array is empty:

function findSmallestElement(arr) {
  return arr.reduce((a,b) => a < b ? a : b); //throws TypeError if arr is an empty array 
}

So I handled it by throwing in a quick if statement before the reduce() method, as shown below. I'm wondering, is there a more elegant/concise way to do this, given that I must return 0 if the array is empty?

function findSmallestElement(arr) {
  if (arr.length === 0) return 0;
  return arr.reduce((a,b) => a < b ? a : b);
}
like image 573
sharethelove Avatar asked Feb 03 '20 04:02

sharethelove


People also ask

How reduce () works in JavaScript?

The reduce() method executes a user-supplied "reducer" callback function on each element of the array, in order, passing in the return value from the calculation on the preceding element. The final result of running the reducer across all elements of the array is a single value.

How do you create a JavaScript reduce?

Introduction to the JavaScript Array reduce() methodFirst, declare an array of three numbers 1, 2 and 3. Second, declare the sum variable and set its value to zero. Third, in the for loop, add up the elements of the numbers array to the sum variable. After the loop, the value of the sum variable is 6.

What is reduce in JavaScript with example?

reduce() method in JavaScript is used to reduce the array to a single value and executes a provided function for each value of the array (from left-to-right) and the return value of the function is stored in an accumulator. Syntax: array.reduce( function(total, currentValue, currentIndex, arr), initialValue )


1 Answers

You can use the conditional operator and spread into Math.min:

const findSmallestElement = arr => arr.length === 0
  ? 0
  : Math.min(...arr);
console.log(findSmallestElement([1, 2, 3]));
console.log(findSmallestElement([]));

But

given that I must return 0 if the array is empty?

I think this is a mistake, or at least should be considered to be a mistake. An array which is empty does really not have a minimum value. If the array is empty, you might consider returning something other than an ordinary number, something which couldn't be considered to be an ordinary minimum value. It's also unintuitive for, for example, findSmallestElement([-1]) to return -1, but findSmallestElement([]) to return 0.

You might emulate the functionality of Math.min instead, and return Infinity:

const findSmallestElement = arr => Math.min(...arr);
console.log(findSmallestElement([1, 2, 3]));
console.log(findSmallestElement([]));

Or maybe return null. Returning 0 is confusing.

like image 141
CertainPerformance Avatar answered Oct 04 '22 21:10

CertainPerformance