There are three problems in your code.
First, counter=numbersord[-1]+numbersord[-2]
is incorrect. Trying to get a negative index from an array, just returns undefined
, since there is nothing there. It's not flipping and getting from the end, to do that, you need to explicitly pass arrayLength - negativeIndex
to get things from the end:
const arr = ["a", "b", "c", "d", "e"];
console.log(arr[1]);
console.log(arr[2]);
console.log(arr[-1]);
console.log(arr[-2]);
console.log(arr[arr.length - 1]);
console.log(arr[arr.length - 2]);
Second, numbers.sort()
is not correct. It sorts using lexicographical order, not numeric, where 1 < 2
but also 10 < 2
. You need to sort numbers properly (check the link for more information):
const arr = [1, 2, 10, 20]
arr.sort();
console.log("default (lexicographical) sort", arr);
arr.sort((a, b) => a - b);
console.log("ascending sort", arr);
arr.sort((a, b) => b - a);
console.log("descending sort", arr);
Finally, if(numbersord[0] === -numbersord[0])
this condition is useless. The only number that is equal to a negative of itself is zero:
console.log(0 === -0);
console.log(1 === -1);
console.log(42 === -42);
console.log(Infinity === -Infinity);
console.log(NaN === -NaN);
However, that's not useful to check for. The logic there (essentially) checks if the array starts with zero and if it does, it reverses it and takes the first two results. If it doesn't start with zero, it tries to take the last two elements of the array.
However, if you simply sort in descending order you get all of that for free and you can take the first two items every time.
So, with these changes, your code looks like this
function largestPairSum(numbers)
{
let counter =0;
//perform a descending sort
let numbersord = numbers.sort((a, b) => b - a);
//always take the first two items
counter=numbersord[0]+numbersord[1]
return counter
}
console.log(largestPairSum([10, 14, 2, 23, 19]))// --> 42 (i.e. sum of 23 and 19)
console.log(largestPairSum([99, 2, 2, 23, 19])) // --> 122 (i.e. sum of 99 and 23)
console.log(largestPairSum([-10,-20,-30,-40])) // --> -30 (i.e sum of -10 and -20)