JavaScript function to calculate the sum of an array while excluding the highest and

I'm currently working on a challenging kata in codewars, but I'm encountering some difficulties. My goal is to calculate the sum of all elements in an array except for the highest and lowest values.

This is my current implementation:

function sumArray(array) {

  let largestVal =  Math.max(array);
  let lowestVal =  Math.min(array);
  let total =  0;

  let arrLength = array.length;

  console.log(`The lowest number is: ${lowestVal}`);
  console.log(`Array is: ${array}`);
  console.log(`Total is: ${total}`);
  console.log(`The larget number is: ${largestVal}`);
  return  // [QUESTION] <= having problems in how to return the sum of each element except the largest and lowest values.  
}

Your help is much appreciated!

EDIT-1: Updated code with @WLatif implementation

function validate(array) {
  if (typeof array === 'object' && array instanceof Array && array.length > 1) {
    return 1;
  } else {
    return 0;
  }
}

function sumArray(array) {
  if (validate(array)) {
    let sorted = array.sort(function (a, b) { return a - b });
    let largestVal = sorted.slice(-1).pop();
    let lowestVal =  sorted[0];
    let total =  array.reduce( function(prev, curr) { return prev + curr; }, 0 );
    let arrLength = array.length;

    console.log(`The lowest number is: ${lowestVal}`);
    console.log(`Array is: ${array}`);
    console.log(`Total is: ${total}`);
    console.log(`The larget number is: ${largestVal}`);
    return (total- lowestVal - largestVal);
  } else {
    console.log(`Not a valid array`);
  }

}

The error message I'm receiving is:

Not a valid array ✘ Expected: 0, instead got: undefined

What am I missing?

Here are the instructions:

Sum all the numbers of the array except the highest and the lowest element (the value, not the index!).
(Only one element at each edge, even if there are more than one with the same value!)

Example:

{ 6, 2, 1, 8, 10 } => 16
{ 1, 1, 11, 2, 3 } => 6


If array is empty, null or None, or if only 1 Element exists, return 0.

Answer №1

To achieve this, start by arranging the array in ascending order and then carry out the necessary operations while ignoring the smallest and largest elements.
Check out the code snippet below:
Good luck!
Edit 1: included validation scenarios.

function validate(array) {
  if (typeof array === 'object' && array instanceof Array && array.length > 1) {
    return 1;
  } else {
    return 0;
  }
}

function sumArray(array) {
  var sorted = array.sort(function(a, b) {
    return a - b
  });
  console.log(`The lowest number is: ${sorted[0]}`);
  console.log(`Array is: ${array}`);
  console.log(`Total is: ${sorted.reduce(function(a, b) { return a + b; }, 0)}`);
  console.log(`The larget number is: ${sorted.slice(-1).pop()}`);
  return sorted.slice(1, -1).reduce(function(a, b) {
    return a + b;
  }, 0);
}

// ideal case
var points = [40, 100, 1, 5, 25, 10];
if (validate(points)) {
  console.log(`sum of numbers except smallest and largest number is: ${sumArray(points)}`);
} else {
  console.log("Array validation unsuccessful");
}

//empty array case
var points = [];
if (validate(points)) {
  console.log(`sum of numbers except smallest and largest number is: ${sumArray(points)}`);
} else {
  console.log("Array validation unsuccessful");
}

// single element case
var points = [40];
if (validate(points)) {
  console.log(`sum of numbers except smallest and largest number is: ${sumArray(points)}`);
} else {
  console.log("Array validation unsuccessful");
}

//other data type case
var points = "x";
if (validate(points)) {
  console.log(`sum of numbers except smallest and largest number is: ${sumArray(points)}`);
} else {
  console.log("Array validation unsuccessful");
}

//null case
var points = null;
if (validate(points)) {
  console.log(`sum of numbers except smallest and largest number is: ${sumArray(points)}`);
} else {
  console.log("Array validation unsuccessful");
}

Answer №2

function calculateSum(array) {
    if (array == null)
    {
        return 0;
    }
    else if (array.length >= 3)
    {
        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;
    }
    else
    {
        return 0;
    }
}

Answer №3

I believe there is a way to make this solution more succinct. Firstly, we handle the edge cases, then proceed to sort the array and compute the sum of the elements in between.

function calculateArraySum(arr) {
      // account for edge cases
        if(arr == null) return 0 
        if(arr.length < 3) return 0
    
        let sortedArr = arr.sort((x, y) => x - y) 
        let totalSum = 0 
      
        for(let j = 1; j < sortedArr.length - 1; j++){
          totalSum = totalSum + sortedArr[j];
        }
        return totalSum
    }

or

function calculateArraySum(arr)  {
    if(arr && arr.length > 1) {
        const sortedArr = arr.sort((x,y) => x - y).slice(1, -1)
        return sortedArr.reduce((acc, currentVal) => acc + currentVal, 0)
    }

    return 0
}

Answer №4

Here is a function that might suit your needs:

const calculateSumWithoutMinMax = (arr) => {
    const maxVal = Math.max.apply(Math, arr);
    const minVal = Math.min.apply(Math, arr);
    const totalSum = arr.reduce((acc, val) => acc + val, 0);

    console.log(`The minimum number is: ${minVal}`);
    console.log(`Array values: ${arr}`);
    console.log(`Total sum: ${totalSum}`);
    console.log(`The maximum number is: ${maxVal}`);

    return totalSum - maxVal - minVal;
}

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

Utilize a directive every instance

I need to implement an angular directive that triggers before all events like ng-click whenever the view value changes. This directive should be called as the first action when the view is changed. Check out the JSFiddle example. angular.module('myA ...

Tips for triggering onclick before changing to a new page?

Currently, I am developing a React application and have encountered the following situation: <a href={link} variant="primary" onClick={this.onClickDoSomething}> here. </a> My goal is for the onClick event to trig ...

The Ajax response is not showing up within the success function in jQuery Mobile

Recently, I have been working on creating a simple login form with username and password fields using jQuery Mobile. The validation for the username and password is supposed to be done through an ajax page. Surprisingly, everything was working perfectly ...

Best practices for assigning values to model field in EXT JS are as follows:

I'm facing an issue with a certain model structure: Ext.define('my.workspace.Area', { extend: 'Ext.data.Model', idProperty: 'id', fields: [ {name: 'id', type: 'string'}, {n ...

Setting up Jplayer as an audio player: A step-by-step guide

I am looking to incorporate a Jplayer audio player into my project, but I am struggling to find any documentation or resources that provide instructions on what components to include and how to set it up. If anyone has experience with using the Jplayer au ...

When the tabBar is hidden on a particular screen, a gray area is shown at the bottom of the page in the Expo app

I am currently working with nested routes using expo-router. When attempting to hide the tabBar for a specific page, I noticed that it still displays a gray area. To address this issue, I have set the display option to none in the tabBarStyles options and ...

"Comparison: Using jQuery's append() vs native JavaScript's appendChild

Take a look at this example code snippet: function insertText(){ var newText = document.createTextNode(" Inserted text dynamically. "); var paragraph = document.getElementById("p1"); paragraph.appendChild(newText); $("#p1").append("HELLO") ...

The second node child process encounters execution issues in Linux

For a challenge, I needed to find a way to automatically restart my bot within itself. After some trial and error, I came up with a solution. However, when testing on a Raspberry Pi via ssh, the process exits after the first child process ends. Surprisingl ...

Why are my images being converted to strings when I submit a post request?

Check out the screenshot https://i.sstatic.net/RR3Rp.png. I'm experiencing issues with image corruption. I'm attempting to upload images using axios post, but it seems like axios is not processing my images correctly. My code is divided into two ...

Error occurred due to an invalid element type with the imported React component

Using a component imported from an npm package in two different apps has resulted in unexpected behavior. In one app, the component functions perfectly as expected. However, in the other app, an error is raised: Element type is invalid: expected a string ...

Date discrepancy detected on AWS EBS server; however, it is operating seamlessly on the local environment

Whenever deployed on an AWS server, there seems to be a recurring miscalculation. Background: All dates stored in my MongoDB are in UTC format. I need them converted to IST before exporting them to Excel. While my code functions flawlessly on my local m ...

Can the position of the popover be customized using the right and top properties?

Utilizing Bootstrap popover within a gantt chart, I am dynamically adjusting the position of the popover based on mouse hover. popover.css('left', event.pageX + 'px'); popover.css('top', event.pageY+ 'px') However, ...

WordPress admin-ajax.php not receiving Ajax call

Trying to implement AJAX in a WordPress admin submenu to call a function, I encountered the following issue: jQuery('#deleteProj').submit(ajaxSubmit); function ajaxSubmit(){ var tobeDeleted = jQuery(this).serialize(); alert(tobeDeleted); ...

Utilize JavaScript to communicate with the backend server

I'm embarking on my first Cordova application, utilizing HTML, CSS, and JavaScript. My current objective is to trigger a local server call upon button click, with the intention of logging something to confirm functionality. However, I'm encounter ...

Ways to fill the option selections using the service

I am currently working on an Angular application where I need to populate dropdown lists from backend data. .component.ts public getMemberCodes() { let baseUrl = `/endpoindAPI`; this._restfulService .restfulGetData(baseUrl) .subscribe( ...

Issue with Angular 18 component not being displayed or identified

Recently, I began building an Angular 18 application and encountered an issue with adding my first component as a standalone. It appears that the app is not recognizing my component properly, as it does not display when added as an HTML tag in my app.compo ...

What is the reason behind the array.map() function not altering the original array?

I attempted to increment each element of my array by one, but was having trouble. Here is what I tried: myArray=[1,2,3] myArray.map(a=>a+=1) // also tried a++ and a=a+1 console.log(myArray) // returns [ 1 , 2 , 3 ] Unfortunately, this method did not w ...

What is the process for incorporating custom controls into the Mantine Embla Carousel within a Next.js environment?

Check out this code snippet: import React from "react"; import { Container } from "@mantine/core"; import { Carousel } from "@mantine/carousel"; import { ArticleCard } from "@/components"; import { cards } from " ...

Understanding the fundamentals of parseInt() and radix conceptsORExploring

Could you clarify the concept of radix in relation to parseInt()? I'm struggling to grasp how the string argument varies with different bases/radix. ...

Ways to confirm non-null values and bypass the row if it is

I have been attempting to compare 2 dates in order to appropriately display data in a table. I have tried the following approach: ${this.dateToCompare.getTime()} > ${row.CreateDate.getTime()} However, there is an issue where CreateDate has a null value ...