Javascript Equivalent to the PHP array_values function

This Javascript function is performs in the same way as the PHP function array_values($array). There are variations of the function to remove null, blank, or any falsey values from a Javascript array, below.

function array_values(array) {
    return array.filter(Boolean);
}

Example:

// an example array with empty and null values
array = [null, "", 1, 0, "0", , , , 2, "hello", -1, , false, 5];

cleanarray = array_values(array); // call the function defined above

Produces the result:

[1,"0",2,"hello",-1,5]

The resulting array has null, empty, "" and FALSE values removed.

Example 2:

It's just as easy to use Javascript without defining the PHP array_values function.

cleanarray = array.filter(Boolean);

 -- or --

cleanarray = array.filter(n => n);

All produce the same result:

[1,"0",2,"hello",-1,5]

A short explanation:

cleanarray = array.filter(Boolean); // is a short way to say the line below:
cleanarray = array.filter(n => Boolean(n) === true); // which is a short way to write the function below:
cleanarray = array.filter(array_values); // calling the function below:

function array_values(n) {
    if (Boolean(n) === true) {
        return n;
    }
}

Javascript arrays with non-numeric keys

The PHP function array_values(n) returns an array with keys re-ordered numerically and null / falsey values removed.  The Javascript function at the top of the page in blue removes all falsey values and reorders keys numerically.

In Javascript all arrays have numeric keys anyway, so this doesn't correspond to PHP exactly.  In order to use associative keys, in Javascript you need to define an object associative array. In this way the "array" keys can be any strings, but it's an object not an array.

It's still possible to do...

Use this function if your Javascript array is an Object with keys as strings to remove falsey values.

function array_values(arrayObj) {
  tempObj = {};
  Object.keys(arrayObj).forEach((prop) => {
    if (arrayObj[prop]) { tempObj[prop] = arrayObj[prop]; }
  });
  return tempObj;
};

cleanarray = array_values(array); // call the function the same way

Copyright © Lage.us Website Development | Disclaimer | Privacy Policy | Terms of Use