0

I need to check if a number is present in an array of number that I get from PHP, and if yes render a data coming from iosocket. But for some reason this code won't work. The array return 20, 25 and the number to check is 20 f.example

<script>
var negozi_seguiti = <?php echo json_encode($negozi_seguiti); ?>;
var post = io('http://1clickfashion.com:3002');
post.on("test-channel:App\\Events\\Post", function(message){
  // increase the power everytime we load test route 
  alert(negozi_seguiti);
  if (jQuery.inArray(negozi_seguiti, message.data.negozio) == -1) {
    $('#timeline').addClass("timeline");
    $('#timeline').prepend(message.data.timeline);
    $('#rocket').hide();
  }
});
</script>

What i'm wrong?

2
  • 2
    jQuery.inArray( value, array [, fromIndex ] ) you seem to be passing arguments in the wrong order Commented Oct 25, 2017 at 8:33
  • Not related, but make it a habit to use === instead of == Commented Oct 25, 2017 at 8:35

2 Answers 2

3

You misused inArray, you inverted arguments, use it like this :

var arr = [20, 21];

console.log($.inArray(20, arr))
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


I also suggest you tu use indexOf which works the same way but is called directly on the array reducing the risk of doing a mistake like this :

var arr = [20, 21];

console.log(arr.indexOf(20));

It makes your code clearer, you get rid of jQuery, and finally it is faster.

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

1 Comment

unfortunately not work arry is output array:2 [▼ 0 => 25 1 => 20 ]
0

If you are getting proper value in your array negozi_seguiti variable then you need to change $.inArray('search_value', 'yourarray') like bellow.

var negozi_seguiti = <?php echo json_encode($negozi_seguiti); ?>;
var post = io('http://1clickfashion.com:3002');
post.on("test-channel:App\\Events\\Post", function(message) {
  // increase the power everytime we load test route 
  alert(negozi_seguiti);
  if (jQuery.inArray(message.data.negozio, negozi_seguiti) == -1) {
    $('#timeline').addClass("timeline");
    $('#timeline').prepend(message.data.timeline);
    $('#rocket').hide();
  }
});

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.