-1

I 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.

Am I on the right track?

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

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

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

I think Array.reduce can be used somehow?

var sum = numArray[2] + numArray[3]; gives me two numebrs together and not their sum.

How do I do math function sum rather than combined two variables into one?


Edit: DrafsApp for Mac was adding two values "2" and "2" into "22"

I had to change the code to this and it works:

var sum = Number(numArray[2]) + Number(numArray[3]);
ggorlen
  • 44,755
  • 7
  • 76
  • 106
slyfox
  • 35
  • 5
  • yeah, you are and it is giving me sum of two number exactly what you expected... – DecPK Jun 06 '21 at 15:47
  • 2
    _"gives me two numbers together"_: sounds like you're using strings and not integers, so it suggests your array in your question is wrong. – Andy Jun 06 '21 at 15:50
  • @slyfox If your array is strings, not numbers, please edit the post to show that as a [mcve]. Thanks. – ggorlen Jun 06 '21 at 15:59

1 Answers1

-1

The code is returning the sum as expected.

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

numArray.sort((a, b) => a - b);
//Sorted array - [1, 1, 2, 2, 3, 4]

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

console.log(sum);
jateen
  • 642
  • 3
  • 13
  • I was getting 22 because DraftsApp adds the two values together. This adjustment works: ```var sum = Number(numArray[2]) + Number(numArray[3]);``` – slyfox Jun 06 '21 at 15:52
  • @slyfox this only happens if you have array of strings, not numbers. the code u suggested in the question contains only numbers. – Dmitriy Frolov Jun 06 '21 at 16:00