How to check if at least one item of the array has value equal to or greater than 2

Asked

Viewed 2,833 times

5

I have the following array:

array[0,2,0,0];

I need to create a function that returns me true if at least one array item has value equal to or greater than 2

  • What have you tried?

  • 2

    Interesting question, I will join the party and give an answer too :) This value "2" is fixed or dynamic?

  • set, but in real life this array has up to 2,000 positions.

  • But I want to know if at least one of the indexes is equal to or greater than 2

  • indices or values?

  • I need to know if at least one item has a value equal to or greater than 2

  • 2

    Drive-thru solution: [0, 2, 0, 0].filter((i) => { return i >= 2 }).length > 0

  • 1

    Has any response helped solve the problem and can address similar questions from other users? If so, make sure to mark the answer as accepted. To do this just click on the left side of it (below the indicator of up and down votes).

  • It helped yes thanks for reminding me

Show 4 more comments

7 answers

10

You can filter and check the size of the resulting array as below:

var teste = [0,2,0,0];

function verificar(array) {
  return array.filter(function(item) {
    return item >= 2;
  }).length > 0;
}

console.log(verificar(teste));

  • Your fiddle is giving error. wanted to see it working. Fastly error: Unknown Domain: stacksnippets.net. Please check that this Domain has been Added to a service. Details: cache-gru17123-GRU

9


Try user the function of the array some

Check if there is an element whose value is equal to 2

var x = [0, 0, 2, 0];

function isTwo(value) {
  return value === 2;
}

var y = x.some(isTwo);

console.log(y);

Check if there is an element greater than or equal to 2

var x = [0, 0, 1, 0];

function maiorQueUm(value) {
  return value >= 2;
}

var y = x.some(maiorQueUm);

console.log(y);

With the Arrow functions ES6 would be even simpler:

var x = [0, 0, 1, 0];
var y = x.some(it => it >= 2);

var w = [0, 0, 2, 0];
var z = w.some(it => it >= 2);

console.log(y, z);

  • 3

    Your answer makes sense, but would suggest to change in the sense that the question says, GREATER OR EQUAL. =)

  • I think that’s the cleanest answer

  • It is also the most performative, since the execution will stop in the first true.

7

Here are several different ways:

var arraryValida = [0, 2, 0, 0];
var arraryInvalida = [0, 1, 0, 0];
var valor = 2;

function testeFor(arr, match) {
    for (var x = 0, l = arr.length; x < l; x++) {
        if (arr[x] >= match) return true;
    }
    return false;
}

function testeMax(arr, match) {
    return Math.max.apply(Math.max, arr) >= match;
}

function testeSome(arr, match) {
    return arr.some(nr => nr >= match);
}

[testeFor, testeMax, testeSome].forEach(function(fn, i) {
    console.log(fn.call(null, arraryValida, valor));
    console.log(fn.call(null, arraryInvalida, valor));
	console.log(i, '----');
});

jsFiddle: https://jsfiddle.net/aLcctzq1/1

  • reduce() is clearly slower your suggestions?

  • 1

    @durtto in this case did not suggest the reduce because it doesn’t seem semantic with the functionality of looking for a true or false.

  • @durtto some of the answers served?

  • 1

    I am still evaluating a criterion to choose the correct one. I am testing some concepts contained in all answers.

6

According to your question, it is enough to know if there is any number greater than or equal to two, in this case, a single loop is sufficient...

function checkArray(myArray) {
    for (i = 0; i < myArray.length; i++) { 
        if(myArray[i] >= 2){
          return true;
        }
    }
    return false;
}

var myArray = array[0,2,0,0];
alert(checkArray(myArray));

5

Here’s a simple way to know indexes:

function checkIndexTwoOrLarger(arr) {
    var achou = false;
    arr.forEach(function(v, i) {
        if (i >= 2)
           achou = true;
    });
    return achou;
}
checkIndexTwoOrLarger([0,0,0,2]);

To values, it would be something like that:

function checkValueTwoOrLarger(arr) {
    var achou = false;
    arr.forEach(function(v, i) {
        if (v >= 2)
           achou = true;
    });
    return achou;
}
checkValueTwoOrLarger([0,0,0,2]);

3

Array#some is the best option:

function funcaoMaiorIgualQueDois(element, index, array) {
  return element >= 2;
}

var  res = [0,2,0,0].some(funcaoMaiorIgualQueDois);
console.log(res);

  • there’s something wrong there

3

In the series of questions the AP is asking ([1], [2]), Much alike, I will insist on simplicity, performance and even legibility, although the latter is a subjective way of evaluating. I would do with a for simple and unwittingly thinking you’re optimizing when you use a cache the size of array (I have shown that this does not work in modern JS mechanisms):

function temValor(array) {
    for (var i = 0; i < array.length; i++) if (array[i] >= 2) return true;
    return false;
}
var array = [0, 5, 1, 2];
console.log(temValor(array));

If you want to generalize the limit:

function temValor(array, limite) {
    for (var i = 0; i < array.length; i++) if (array[i] >= limite) return true;
    return false;
}
var array = [0, 5, 1, 2];
console.log(temValor(array, 2));

I put in the Github for future reference.

Browser other questions tagged

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