Remove empty positions from an array

7

I'm passing array via GET to PHP and then sending to the client side (JavaScript). When I get it it looks like this:

m_prod = [5,,,,,,,,6,,,,,,];

In other words, it is including a space in the positions that do not contain a value! How can I remove these spaces in JavaScript?

<?php
    $m_prod = trim($_GET['m_prod']);
    print("<SCRIPT language=javascript> m_prod = \"$m_prod\"; </SCRIPT>");
?>
    
asked by anonymous 19.11.2014 / 15:47

2 answers

13

You can use the filter function as follows:

var m_prod = [5, , , , , , , , , ,6 , , , ];

var resultado = m_prod.filter(function(ele){
  return ele !== undefined;
});

console.log(resultado);  // [5,6]
    
19.11.2014 / 15:50
8

If the problem comes from PHP I think it should solve in PHP.

To filter an array of empty elements:

$m_prod = array_filter($m_prod);

In case there are numbers inside the array then we have to be extra careful because the 0 is set to false and is removed from the array. So you can do:

$m_prod = array_filter($m_prod, function($value) {
  return !empty($value) || $value === 0;
});

To pass this to JavaScript you can render like this:

echo '<script>';
echo 'm_prod = '.json_encode($m_prod);
echo '</script>';
    
19.11.2014 / 16:54