0

If I want to skip a number of items in a for loop in PHP, I might use PHP's native in_array(needle,haystack); function in the following manner:

PHP

$Fruit = array('Apple','Banana','Cucumber','Grapes','Pear','Tomato');
$Salad = array('Tomato','Cucumber');
$Herb = array('Banana');

$countFruit = count($Fruit);

for ($i = 0; $i < $countFruit; $i++) {
if (in_array($Fruit[$i],$Salad)) continue;
$fruitBowl[] = $Fruit[$i];
}

This will give me a $fruitBowl of:

array('Apple','Banana','Grapes','Pear');

I realize I could use the much simpler

$fruitBowl = array_diff($Fruit,$Salad);

but bear with me - I'm making up this example as I go along.

How do I reproduce this (or something similar) in Javascript?

Here's what I have come up with:

Javascript

var Fruit = ['Apple','Banana','Cucumber','Grapes','Pear','Tomato'];
var Salad = ['Tomato','Cucumber'];
var Herb = ['Banana'];
var fruitBowl = [];

var countFruit = Fruit.length;

for (var i = 0; i < countFruit; i++) {
if (Salad.indexOf(Fruit[i]) !== -1) {continue;}
fruitBowl.push(Fruit[i]);
}

Having got this far, my question is specifically this:

Is the Javascript

if (Salad.indexOf(Fruit[i]) !== -1) {continue;}

now (in 2015) the standard way to reproduce

if (in_array($Fruit[$i],$Salad)) continue;

in PHP?

Or is there a less obscure way of going about it?

N.B. I understand that jQuery has inArray and Prototype has Array.indexOf but I'm just looking for a plain JavaScript solution.

Rounin
  • 27,134
  • 9
  • 83
  • 108
  • possible duplicate of [JavaScript equivalent of PHP's in\_array()](http://stackoverflow.com/questions/784012/javascript-equivalent-of-phps-in-array) – Jonny C Apr 29 '15 at 12:53
  • possible duplicate of [array.contains(obj) in JavaScript](http://stackoverflow.com/questions/237104/array-containsobj-in-javascript) – Halayem Anis Apr 29 '15 at 12:56

0 Answers0