logo

Sum without highest and lowest number

Sum all the numbers of a given array ( cq. list ), except the highest and the lowest element ( by value, not by index! ).


My code:


                        function sumArray(array) {
                            if (Array.isArray(array) && array.length >= 2) {
                              let sortArr = array.sort((a, b) => a - b);
                              let result = 0;
                              for (let i = 1; i < sortArr.length - 1; i++) {
                                result += sortArr[i];
                              }   
                              return result;
                            } else {
                              return 0;
                            }
                          }                                              
                        
                    


And that's the best solution among all users:


                        function sumArray(array) {
                            if (array == null) {
                              return 0;
                            } else if (array.length < 2) {
                              return 0;
                            } else {
                              array = array.sort(function(a,b) {return a - b;});
                              var total = 0;
                              for (var i = 1; i < array.length - 1; i++) {
                                total += array[i];
                              }
                              return total;
                            }
                          }
                    

New things I learned today: