Search code examples
javascriptarraysmultidimensional-array

Testing Existence of a Sparse Array Element in JavaScript?


What's the best way to test for the existence of an array element in a structure several layers deep? For instance:

if (typeof arr[a][b][c] === 'undefined') { ...do something... }

If [a] or [b] don't exist, we won't be able to test for [c].

Are there underscore or lodash functions to handle this?


Solution

  • It you need it in many places you can create a function:

    function get(obj, props) {
      return props.reduce(function(x, p) { return x && x[p] ? x[p] : null }, obj)
    }
    
    if (get(arr, [a, b, c])) ...
    

    Works with objects and arrays:

    var obj = [0, {a: [0, 'value', 2]}, 2]
    get(obj, [1, 'a', 1]) //=> 'value'
    get(obj, [1, 'a', 8]) //=> null