8

I created an array of integers and wanted to know if it had one or more negative values in it.

I do not want to create a for() loop and check if each element in the array is positive or negative because I only want to return once (ex: I don't want my function to "return false;" a million times).

One option I considered was multiplying each value in the array by the absolute value of its reciprocal, so I get an array of 1s or -1s (or undefined if value is 0) and then I could sum all of the values in this second array to see if it equals the length of the array.

However, the problem with this method is it does not account for 1/0, and also it is tedious. I want to know if there is a faster way to check if an array contains at least one negative value.

--from a beginner JavaScript programmer

4
  • 2
    Look at Array#some-
    – Ori Drori
    Commented Jun 13, 2017 at 21:15
  • const hasNegative = arr.some( x => x < 0 );
    – Paul
    Commented Jun 13, 2017 at 21:17
  • Also a function can only return once. If you return false when you find a negative value the function will be done and the loop won't continue running.
    – Paul
    Commented Jun 13, 2017 at 21:27
  • What if there are multiple negative values? Do you return the smallest or the first negative value? Also what if there is no negative value?
    – Mμ.
    Commented Jun 13, 2017 at 21:32

4 Answers 4

21

You could leverage Array.prototype.some which will return true or false if an item in the array matches the given condition. It'll also stop checking remaining values if the condition matches an element:

let values = [1, 4, 6, -10, -83];
let hasNegative = values.some(v => v < 0);
0
2

why do you find min value in array? see

JavaScript: min & max Array values?

Math.min(...array) 
1
  • short and to the point
    – Tadas V.
    Commented Jan 15, 2022 at 16:13
1

This will only return 1 value and break as soon as a negative is found.

function doesArrayContainNegative(array){

  //if negative is found return true (breaking loop)
  for(var arr of array){
  	if(arr < 0) return true;
  }
  
 //if no elements are negative return false
  return false;
}

var array1 = [9, -3, 5, 8]
console.log(doesArrayContainNegative(array1))

0

What's the issue with the for loop needing to return false all the time?

fucntion containsNegative(myArray)
    for(var i = 0; i < myArray.length(); i++)
    {
        if(myArray[i] < 0){
            return true;
        }
    }
    return false;
}

and if you wanted to get the amount of negative numbers

fucntion getNegative(myArray)
    var count = 0;
    for(var i = 0; i < myArray.length(); i++)
    {
        if(myArray[i] < 0){
            count++
        }
    }
    return count;
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.