0

this is the snippet: this code is not working, the problem it is not recognizing the array inside the array.

how can i improve it?

thanks!

<!DOCTYPE html>
<html>
<body>

<p>The new ECMASCRIPT 5 method isArray returns true when used on an array.</p>

<p id="demo"></p>

<script>
function findApple(arr, item) {
  var count = 0;
  for (var i = 0; i < arr.length; i++) {
    if (Array.isArray(arr[i])) {
       findApple(arr[i], item);
    }
    else if (arr[i] == "apple") {
      count++;
    }
  }
  return count;
}
var one = ["apple", "apple", ["orange", "apple", "banana"]];

var data = findApple(one, "apple");
alert(data);
var item = document.getElementById("demo").innerHTML = data;
</script>

</body>
</html>
3
  • 2
    The problem is here findApple(arr[i], item); - you're not using the return value. Commented Sep 28, 2016 at 13:54
  • 1
    it is not recognizing the array inside the array yeah, I don't think that is correct. Commented Sep 28, 2016 at 13:56
  • on a side note, shouldn't the apple in the else if be item otherwise there is no point in passing the item var in Commented Sep 28, 2016 at 13:58

3 Answers 3

1

Use count += findApple(arr[i], item);

Sign up to request clarification or add additional context in comments.

Comments

0

You have the following problem:

if (Array.isArray(arr[i])) { findApple(arr[i], item); }

As you wrote the script, you know that findApple RETURNS something. So the right syntax would be:

var result=findApple();

As you want to pass it back to the callee simply do:

 count+=result;

Comments

0

function findApple(arr, item) {
  var count = 0;
  for (var i = 0; i < arr.length; i++) {
    if (Array.isArray(arr[i])) {
       count+=findApple(arr[i], item);
    }
    else if (arr[i] == "apple") {
      count++;
    }
  }
  return count;
}
var one = ["apple", "apple", ["orange", "apple", "banana"]];

var data = findApple(one, "apple");
alert(data);
var item = document.getElementById("demo").innerHTML = data;
<!DOCTYPE html>
<html>
<body>

<p>The new ECMASCRIPT 5 method isArray returns true when used on an array.</p>

<p id="demo"></p>



</body>
</html>

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.