Why does passing in a number as a string into an array cause the wrong result?

true or false? when an array is passed to a method, a new array is created and passed to the method.
the array size is fixed after it is created
array methods java
chapter 8 checkpoint questions introduction to java programming
c# function with variable number of arguments
difference between spread and rest operator in javascript
params string c#
c# params pass array

I have built a function that allows you to pass through an array and it successfully returns the second highest and second lowest numbers. However, I'm new to error handling and don't understand why this fails:


It works correctly when passing in getNos([5,5,8]); or passing arrays like getNos(["5",8]);.

Can someone explain what's happening here and how to fix it? Thanks for any help here - the function code is below:

function getNos(arr){

if (!Array.isArray(arr) || arr.length == 0 || arr.length == 1 || (arr.every(c => !isNaN(c)) == false)) {
    throw 'Invalid Input';
} else {

    var result;
    var uniqueVals = Array.from(new Set(arr));
    var highest = highestVal(arr);
    var lowest = lowestVal(arr);

    if (uniqueVals.length == 1) {
        result = arr[0] + " " + arr[0];
    } else if (arr.length == 2 || uniqueVals.length == 2) {
        result = highest + " " + lowest;
    } else {
        arr = arr.filter(item => ((item !== highest) && (item !== lowest)));
        var secondHighest = highestVal(arr);
        var secondLowest = lowestVal(arr);

        if (arr.length == 1) {
            arr = arr.slice(arr.indexOf(secondHighest));
            result = highestVal(arr);
        } else {
            result = secondLowest + " " + secondHighest;
    return result;

function highestVal(a) { return a.reduce((a, b) => a > b ? a : b ) };
function lowestVal(a) { return a.reduce((a, b) => a < b ? a : b ) };

Follow carefully the logic var uniqueVals = Array.from(new Set(arr)). What will this line return when you have arrays such as [5,"5",8] vs [5,5,8] vs ["5", 8]?

A Set stores unique value of a type. "5" is of type string whereas 5 is of type number. The highestVal and lowestVal functions can compare "5" and 8, no problem, but since an array could include either a string or number for either 5 or 8 as well, then you will get funny values being returned.

To fix this, before passing arr to the Set, you need to convert all values to a single type, preferably number.

let numberArr = arr.map(el=>+el) is one way of doing that, but you may want better data validation than that.

How to pass Arrays to Methods in Java?, How do you declare an array reference variable and how do you create an array? We can pass an array of any dimension to a function as argument. Passing an array to a function uses pass by reference, which means any change in array data inside will reflect globally. Passing Single Element of an Array to Function. We can pass one element of an array to a function like passing any other basic data type variable.

Simple fix would be map the values to numbers before creating the set to avoid having the same numeric values as both string and number in the set


var uniqueVals = Array.from(new Set(arr));


var uniqueVals = Array.from(new Set(arr.map(Number)));

Arrays and references | Think Java, How do you pass an array as a command line argument in Java? This method is sometimes called as call by value-result; Pass by name : This technique is used in programming language such as Algol. In this technique, symbolic “name” of a variable is passed, which allows it both to be accessed and update. Example: To double the value of C[j], you can pass its name (not its value) into the following procedure.

The function does not fail in the sense that it throws an error. For these types of questions please add an example of "expected results".

When you compare strings and numbers in JavaScript, you are relying on implicit coercion to take care of the comparison. In this case it won't throw and error and break anything, it is fine as JavaScript will convert your string to a number and compare (unless its a strict equality === which checks type as well).

Should the result be based off what was passed in? Or after the input has been filtered for numbers only. Or if the input can be converted to valid numbers?

In the case of filter for valid numbers. Filter the input as follows...

  arr = arr.filter(data => typeof data === 'number')

In the case of converting values to a number and removing those that cannot be converted...

  arr = arr.reduce(((acc, el) => {
                       const num = Number(el);
                       if (!Number.isNaN(num)) acc.push(num);
                       return acc;
                     }), []);

Pro Perl, Since this is not a variable, it causes a syntax error when we try to assign to $_[0]. If we chose to return a result rather than modifying the passed argument, then the The key problem here is not that we are passing an array instead of a scalar but If we tried to call capitalize with a literal string value, we would get this error:​  In addition to the Equals method, strings also provide the Compare method, which gives you information about the relative order of strings instead of just a test for equality. This method is preferable to the < , <= , > and >= operators, for the same reasons as discussed above–to avoid C# problems.

GATE AND PGECET FOR COMPUTER SCIENCE AND INFORMATION TECHNOLOGY, , To initialize all elements in an array to zero, all we need to do is initialize the first To pass the whole array to a function, we should only use the name of the An invalid index used with an assignment operator either causes the program to fail costAry[20]; costAry = quantity * price; It is most likely a logic error to leave out  Formal parameters as an unsized array − void myFunction(int param[]) { . . . } Example. Now, consider the following function, which takes an array as an argument along with another argument and based on the passed arguments, it returns the average of the numbers passed through the array as follows −

Chapter 7 Check Point Questions, How do you declare an array reference variable and how do you create an array​? is " + x); System.out.println("The size of numbers is " + numbers.length); 1 public class Test { 2 public static void main(String[] args) { 3 int list[] = {1, 2, 3, 4, 5, 6}; 4 code is written to reverse the contents in an array, explain why it is wrong. In this article. Passing single-dimensional arrays as arguments. Passing multidimensional arrays as arguments. See also. Arrays can be passed as arguments to method parameters. Because arrays are reference types, the method can change the value of the elements.

Array methods, The arrays are objects, so we can try to use delete : let arr = [ "I" So, if we look for false , it finds exactly false and not the zero. If we want It may contain numbers or strings or objects or whatever. As function is applied, the result of the previous function call is passed to the next one as the first argument. 1. read the conversion data from file into an array 2. have a loop that allows the user to continue entering numbers until an end sentinel such as 0 is entered. 3. create a user-defined function that takes arguments of an integer ( between 1-20) , as well as the data conversion array and its size.

  • What is the "wrong result" ?
  • It works correctly when passing in [...] or passing arrays like [...]. So when does it not work?
  • Why? Would you care explaining what your code does and how it will fix OP's question?
  • Because String "5" and number 5 would create separate values in set
  • I see. What will happen then if you pass getNos([5,"4",8])? I don't think that's what OP was asking for...
  • What's wrong with that case? uniqueVals would be [5,4,8]. All the values have to pass OP's isNan test
  • didn't realise it would be such a simple fix, thank you