JavaScript code to find the sum of an array excluding the highest and lowest numbers

My current challenge involves summing all the numbers in an array, except for the highest and lowest elements. It's important to note that if there are multiple elements with the same value as the highest or lowest, only one of each should be excluded.

I've written this code to accomplish the task, but I keep getting NaN as the result:

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

}
console.log(
  sumArray([6, 2, 1, 8, 10])
)  

Answer №1

Here are some key points to consider:

  • The sum function must have an initial value, typically set as 0
  • Making a return statement inside the loop restricts it to just one iteration; move it outside the loop for multiple iterations.
  • To avoid missing out on the last value in the array, ensure your loop iterates until i < array.length - 1
  • Instead of using the sort method with a time complexity of O(nlogn), opt for O(n) by utilizing Math.min and Math.max:

function sumArray(array) {
    return array.length < 2 ? 0
         : array.reduce((a, b) => a + b) - Math.min(...array) - Math.max(...array);
}
console.log(
    sumArray([6, 2, 1, 8, 10])
)  

Note: The code is written in ES6, compatible with major browsers except for Internet Explorer.

For older browser support:

function sumArray(array) {
    return array.length < 2 ? 0
         : array.reduce(function (a, b) {
               return a + b;
           }) - Math.min.apply(null, array) - Math.max.apply(null, array);
}
console.log(
    sumArray([])
)  

When dealing with very large arrays, consider using reduce to fetch minimum and maximum values due to limitations on the number of arguments passed to a function call.

Answer №2

  1. initialize the sum=0
  2. move the return statement outside of the loop
  3. loop until <length-1, not 2

Note in the second example I utilized reduce method to obtain the maximum and minimum values.

both spread (...) and apply will either fail or provide an incorrect result if the array has excessive elements, as they attempt to pass these elements as function parameters.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/max

function sumArray(array) {
  var sum = 0;
  array.sort(function(a, b) {
    return a - b
  });
  for (var i = 1; i < array.length - 1; i++) {
    sum += array[i];
  }
  return sum;
}
console.log(
  sumArray([6, 2, 1, 8, 10])
)

// or without sorting
let arr = [6, 2, 1, 8, 10];
const max = arr.reduce(function(a, b) {
  return Math.max(a, b);
})
const min = arr.reduce(function(a, b) {
  return Math.min(a, b);
})
let sum = arr.reduce(function(a, b) {
  return a + b;
}, 0); // add 
sum -= (min + max);
console.log(sum)

// using only one reduce function (as seen on https://stackoverflow.com/a/43576388/295783):
let minmax = arr.reduce(
  (accumulator, currentValue) => {
    return [
      Math.min(currentValue, accumulator[0]),
      Math.max(currentValue, accumulator[1])
    ];
  }, [Number.MAX_VALUE, Number.MIN_VALUE]
)
sum = arr.reduce(function(a, b) {
  return a + b;
}, 0); // add 
sum -= (minmax[0] + minmax[1]);
console.log(sum)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

jQuery is not updating the div as expected

While typing out this question, I'm hoping to uncover a solution that has eluded me so far. However, just in case... About a year ago, I successfully implemented something similar on another website and went through the code meticulously. Surprisingl ...

What is the best way to tally the elements of a nested object within a group of objects?

I am working with an array of objects that contain nested arrays of objects, similar to what is shown in Code snippet 1. My goal is to calculate the number of records within the nested array where the parent_user_id matches the id. Based on this criteria, ...

Can you conceal a JavaScript function within a specific scope?

Suppose I have two functions a and b that I want to keep within a certain functional scope. Since they share some common code, I decide to extract this shared functionality into another method named support. support should be accessible by both a and b, b ...

What is the best way to show only a specific v-for element in Vue.js?

Is there a way to select a specific item from a v-for loop in vue js? I am using v-for to retrieve Youtube data API items. Each item contains an iframe that should only be displayed when a user clicks on a play button. Currently, all the iframes are shown ...

The AJAX callback is unable to access the method of the jQuery plugin

I have a scenario where I am fetching data from an AJAX response and attempting to update a jQuery plugin with that value within the success callback: $.ajax({ url: '/some/url', type: 'GET', dataType: 'json', succ ...

The React functional component fails to update when triggered by a parent component's setState method

My React component is utilizing apollo to fetch data through graphql class PopUpForm extends React.Component { constructor () { super() this.state = { shoptitle: "UpdateMe", popupbodyDesc: "UpdateMe" } } re ...

How to access a global jquery function variable inside a foreach loop

Is there a way to modify the value of a global jQuery variable inside a foreach loop each time a new model item is encountered? I am looking to update the calendar with new dates but I need access to certain functions within the foreach loop to achieve thi ...

Is it possible to fill dropdown menus on a webpage using jQuery or JavaScript without the need for an ajax call?

Currently, I am looking to populate multiple dropdown lists using jQuery when the page loads rather than relying on ajax responses to events. My Controller is responsible for creating several List objects that will be used for these dropdowns. Right now, I ...

Preparing the data for populating Google charts

I am attempting to showcase Line charts using the Google API. I have tried to format the data from an ASP.net Webmethod as shown below: [WebMethod] public static List<object> GetChartData() { List<object> chartData = new List<obj ...

Challenges with dynamically adding rows using jQuery

I am trying to create a dynamic form that allows users to select a project and then populates tasks based on the selected project from a database query. The user can then enter hours for each task, which are updated based on the project id and task id comb ...

Display modal after drop-down selection, triggered by API response

Currently, I am working on integrating an API to enable users to make payments through a modal. Users should be able to enter an amount and select a payment frequency. I have successfully extracted various payment frequencies from the API response and pop ...

A step-by-step guide on deleting an element within a div using jQuery

I am attempting to delete an HTML element using JQuery like this $('#' + divId + ' .settings_class').remove('.print_settings'); This code does not result in an error or remove the specified html element, however, the selecto ...

IntelliJ does not support the use of newlines within Vue.js component templates

While working with Vue.js in IntelliJ IDEA, I encountered a small problem related to defining component templates. The issue is that IntelliJ seems to struggle when the template spans more than one line and attempts to concatenate them together. For examp ...

Select2 Dropdown Options Do Not Update Background Color

I am currently implementing the Select2 Input CSS/jQuery framework from to assist me in handling multi-select boxes. However, I am facing difficulty in changing the background color of the results when the select box is clicked. To provide a better under ...

Utilizing the power of jQuery's $.each method to dynamically generate HTML select options within an AJAX

I am working with a bootstrap modal that includes a form which requires data from the database. To retrieve this data, I am using PHP as shown below: public function get_view_for_inspection_report_belum_eor(){ $q = $this->inspection->get_view_fo ...

Manipulating arrays and troubleshooting Typescript errors in Vue JS

I am attempting to compare the elements in one list (list A) with another list (list B), and if there is a match, I want to change a property/field of the corresponding items in list B to a boolean value. Below is the code snippet: export default defineCo ...

having trouble setting up create-react-app

I recently started learning about the React ecosystem and just installed Yarn ➜ WebstormProjects yarn --version 0.23.2 Following the documentation, I then proceeded to install create-react-app globally with Yarn ➜ WebstormProjects yarn global add ...

Traverse an SVG element using JavaScript

I have a beautiful star SVG that I created, and I want to use it instead of styling a span to create floating bubbles in my div. However, I'm facing some challenges in adapting my Javascript loop to incorporate the SVG for creating the bubbles, as opp ...

Eliminating the table header in the absence of any rows

I have successfully implemented a Bootstrap table in my React application, where users can add or delete rows by clicking on specific buttons. However, I want to hide the table header when there are no rows present in the table. Can anyone guide me on how ...

Searching for an element with a changing name using jQuery - Struggling with quotes

Looking to navigate my DOM based on the value of an option in a select box. The value of "searchkey" can vary based on user input, for example: searchkey = dell'anno searcheky = dell"anno These options, particularly the first one, can cause issues ...