Sum two specific array numbers

have an array that I need to the following with:

  1. arranged from lowest to highest.
  2. Select the middle two numbers.
  3. Sum the middle two scores.

Example:

var numArray = [2, 1, 3, 1, 4, 2];

numArray.sort((a, b) => a - b);

var sum = numArray[2] + numArray[3];

var sum = numArray[2] + numArray[3]; gives me two numbers together and not their sum in Drafts but Online javascript editors produce the sum of 4.

I had to change the code to this for Drafts to process numbers.

var sum = numArray[2] + numArray[3]

Why is there a difference between online editors that process numbers and Drafts that processes strings?

Full Code that process strings instead of numbers:

var p = Prompt.create();

p.title = "Psychiatric Impairment Rating Scale (PIRS) Impairment";
p.message = '1 - no deficit, 2 - mild impairment; 3 - moderate impairment; 4 - Severe impairment; 5 - totally impaired'
p.isCancellable = true;
p.addButton('OK');

p.addTextField('activitiesOfDailyLiving', 'Self-Care, Personal Hygiene and Activities of Daily Living', '');

p.addTextField('socialRecreational', 'Social and Recreational', '');

p.addTextField('travel', 'Travel', '');

p.addTextField('interpersonalRelationships', 'Interpersonal Relationships', '');

p.addTextField('concentrationPersistencePace', 'Concentration, Persistence and Pace', '');

p.addTextField('resilienceEmployability', 'Resilience and Employability', '');


if (p.show())	{

var activitiesOfDailyLiving = p.fieldValues["activitiesOfDailyLiving"];
var socialRecreational = p.fieldValues["socialRecreational"];
var travel = p.fieldValues["travel"];
var interpersonalRelationships = p.fieldValues["interpersonalRelationships"];
var concentrationPersistencePace = p.fieldValues["concentrationPersistencePace"];
var resilienceEmployability = p.fieldValues["resilienceEmployability"];

var numArray = [activitiesOfDailyLiving, socialRecreational, travel, interpersonalRelationships, concentrationPersistencePace,resilienceEmployability];

alert(numArray);

// 1. Arranged from lowest to highest.
numArray.sort((a, b) => a - b);

// 2. Select the middle two numbers.

//var middleOne = Number(numArray[2]);
//var middleTwo = numArray[3];

//3. Sum the middle two scores.

//(numArray[2] and (numArray[3] are actually strings, not numbers. The easiest way to produce a number from a string is to prepend it with `+`. Alternatively use Number(numArray[2]) + Number(numArray[3])


var sum = numArray[2] + numArray[3];

alert(sum);

const impairmentScore = {2:0, 3:5, 4:10, 5:15, 6:20, 7:30, 8:40, 9:50, 10:50};

var scorePIRS = impairmentScore[sum];

alert(scorePIRS);

var textPIRS = `The Psychiatric Impairment Rating Scale (PIRS) captures behavioural/functional consequences of mental disorders on 6 subscales that each measure a domain of functional impairment on a 5-point scale. The six domains measured include Self-care, Personal Hygiene, and Activities of Daily Living Role Functioning, Social and Recreational Activities Travel Interpersonal Relationships Concentration, Persistence, and Pace Resilience and Employability. Ms. XX's score places him the Impairment Score of ${scorePIRS}%.`

editor.setSelectedText (textPIRS);
}

I think you are on the right track in your own comments in the sample code. You have to convert your array to an array of numbers first. Not just to do the sum, but before you do the sort, or you will be sorting in alpha order, not numeric order.

Something like:

let strArray = [activitiesOfDailyLiving, socialRecreational, travel, interpersonalRelationships, concentrationPersistencePace,resilienceEmployability];
// convert strings to numbers in a separate array
let numArray = strArray.map(n => Number(n));
// sort (default numeric sort will work)
numArray = numArray.sort();
// sum
let sum = numArray[2] + numArray[3];

Script Error: SyntaxError: Cannot declare a let variable twice: ‘numArray’.

Can you please explain what this does ? strArray.map(n => Number(n))

My bad. Edited the example. The second “let” was in error.

I’ve made this error more times than I can count (there’s a pun in there somewhere).

The key to understanding what’s going on are the lines that look like

p.addTextField('activitiesOfDailyLiving', 'Self-Care, Personal Hygiene and Activities of Daily Living', '');

The user enters data into a text field. Even if what the user enters is a numeral, it’s still text as far as JavaScript is concerned. And when JS adds text variables, it returns the concatenation of the text: “1” + “2” = “12”

So you have to convert the strings that look like numbers to you into numbers as JavaScript understands them. The map function that Greg uses on the strArray variable does that by applying the Number function to each element of strArray. That converts the list of strings to a list of numbers, which is why numArray is a list of numbers. (Greg is also using arrow notation, which makes the argument to map compact. I don’t want to get into that.) The newly created numArray list works the way you expect.

Presumably, the online editors that you’ve used in the past have done the same conversion Greg did behind the scenes.

1 Like

Just to follow-up on the first part of your original post, the example code that you posted should (and does for me) work in Drafts as it does in online editors.

I modified it a little so that you could follow your steps in the output.

let numArray = [2, 1, 3, 1, 4, 2];
let strOutput = "Unsorted = " + numArray.join("-") + "\n\n";

numArray.sort((a, b) => a - b);
strOutput += "Sorted = " + numArray.join("-") + "\n\n";

let sum = numArray[2] + numArray[3];
strOutput += "Sum of 3rd + 4th entries = " + numArray[2] + " + " + numArray[3] + " = " + sum.toString();
alert(strOutput);

The output I get is this.

2021-06-06-19.46.37

You should only be getting the behaviour you describe when you are passing in non-numeric values in the array.

Thank you for the explanation. The problem that I am getting is that the numbers are coming from a text file p.addTextField. Thus they are passed on as a string.

Here is what I get after pasting your code into mine:

Screen Shot 2021-06-07 at 9.14.59 AM

My post above covered that issue. Data types need to be converted, so that your values are no longer strings, but numbers, before you “do the math”, as they say…

Yes - as Greg noted previously, and again below, that’s because for that case, your data entry fields are passing in text. That is not the same as the example code you posted originally, which is using numeric values, and I was showing that your example code did work and was not producing the results the post seemed to suggest that it did.

I almost got it. This particular part is confusing to me. I get the general idea that it maps the string array to a number array but I don’t understand how it does it.

strArray.map(n => Number(n))

What should I read to understand this n => Number(n) ?

Try this as a starting point.

https://www.w3schools.com/js/js_arrow_function.asp

// String Array

let strArray = [activitiesOfDailyLiving, socialRecreational, travel, interpersonalRelationships, concentrationPersistencePace,resilienceEmployability];

// convert strings to numbers in a separate array

let numArray = strArray.map(n => Number(n));

  • “=>” Arrow functions allow us to write shorter function syntax.
  • “Number(n)” Number(value) converts a string or other value to the Number type.
  • “strArray.map” The map() method creates a new array populated with the results of calling a provided function on every element in the calling array.

From what I understand, the following happens:

  1. Take a string strArray and map it thereby applying a functioning to each value in the string array.

  2. “n” is the name of a new function, which converts each passed on value to a number. The value is fed from step 1 strArray.map.

Pretty close. Number 2 isn’t quite right. Maybe it will make more sense without the anonymous function syntax. This would do the same thing in old style function syntax:

let numArray = strArray.map(function(n) {
    return Number(n));
});

Map calls a function on each value in the array, and n is the parameter passed as the value for each item as it iterates.