Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nesting array.some() in javascript

Tags:

javascript

I'm wondering about nested uses of Array.some(). Suppose the task is to determine whether three numbers in an array sum to a given value x. I tried the following, but it did not work:

return myArray.some(function(num1){
    myArray.some(function(num2){
       myArray.some(function(num3){
           return num1 + num2 + num3 === x;
       });
    });
 });

Any insight on this would be helpful, including why the above doesn't work.

like image 992
Brian Embry Avatar asked Oct 15 '25 15:10

Brian Embry


1 Answers

You should return the response of each nested myArray.some otherwise, the enclosing method will receive an undefined.

See the code below.

var myArray = [1, 3, 7, 21];
var x = 31;

var opt = myArray.some(function(num1) {
  return myArray.some(function(num2) {
    return myArray.some(function(num3) {
      return num1 + num2 + num3 === x;
    });
  });
});

console.log(opt);
like image 137
void Avatar answered Oct 18 '25 03:10

void



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!