Array with negative numbers javascript

Asked

Viewed 297 times

-1

I am trying to do an exercise where I have that shows the values of 5 numbers that can be positive or negative but only the negative numbers of the array will be shown and also inform how many negative numbers there are. I tried the following code:

function numeros5(n1, n2, n3 ,n4, n5){
    let ray = [n1,n2,n3,n4,n5]
    let  negativo = Number < 0
    return ray.filter(negativo)
}
console.log(numeros5(-5,-2, 4,-3, 6))

1 answer

3


Use the filter is a good option, but it was being used incorrectly, see the correction:

function numeros5(n1, n2, n3 ,n4, n5){
    let ray = [n1,n2,n3,n4,n5];

    return ray.filter( number => number < 0);
}

console.log(numeros5(-5,-2, 4,-3, 6));

The condition was created within the filter, using a Arrow Function.

Documentation: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filtro


To show the amount of numbers, you can use the property length of the returned array:

function numeros5(n1, n2, n3 ,n4, n5){
    let ray = [n1,n2,n3,n4,n5];

    return ray.filter( number => number < 0);
}

const negativos = numeros5(-5,-2, 4,-3, 6);

console.log(negativos.length);

Documentation: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/length


As you receive several numeric parameters in your function, you can declare only one parameter with ... at first:

function numeros5(...ray){
  return ray.filter( number => number < 0);
}

const negativos = numeros5(-5,-2, 4,-3, 6, 8, 9, -7);

console.log(`Números negativos: ${negativos}`);
console.log(`Quantidade de números negativos: ${negativos.length}`);

See that it is very simple and the function receives N parameters.

Documentation: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/rest_parameters

Browser other questions tagged

You are not signed in. Login or sign up in order to post.