22

I'm receiving json data that is aggregated by numerical indexes.

When I'm in my forloop, for example, the index might start at 1, which means in my forloop an error would occur because 0 doesnt exist.

How do I check if a numerical index exists in the javascript array?

HDJEMAI
  • 9,436
  • 46
  • 67
  • 93
somejkuser
  • 8,856
  • 20
  • 64
  • 130
  • Lets see an example of this json data – Musa Jun 21 '13 at 22:48
  • 1
    How could an index *not* exist in an array? What you mean is it's value is `undefined`, right? – acdcjunior Jun 21 '13 at 22:49
  • 1
    Please post an example. Descriptions of problems in questions are often difficult to answer without concrete examples. – CodeMonkeyKing Jun 21 '13 at 22:51
  • You haven't posted any code for us to see why you would have an error, but as a suggestion, have you considered using [Array.prototyp.forEach](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach)? This will most likely solve your problem (unless `Array.length` is broken) without you showing us any code. :/ – Xotic750 Jun 21 '13 at 23:31
  • This is a valid question. Arrays in JavaScript can be sparse. They're basically Objects with some special properties. –  Sep 29 '14 at 15:28
  • @acdcjunior I don't understand why the question has been closed because_it's difficult to tell what is being asked_. It's very clear what was asked. In a numeric array there can be gaps which have to be checked otherwise the script execution ends. – Peter VARGA Aug 23 '20 at 16:01
  • @PeterVARGA that's what I asked. If by "checking" he meant testing if the value is `undefined` or not. Or if he meant something else entirely (which, 7 years later, seems not to be the case). – acdcjunior Aug 24 '20 at 21:01

3 Answers3

37
var a = [1, 2, 3], index = 2;

if ( a[index] !== void 0 ) { /* void 0 === undefined */
    /* See concern about ``undefined'' below.        */
    /* index doesn't point to an undefined item.     */
}
HDJEMAI
  • 9,436
  • 46
  • 67
  • 93
Andreas Louv
  • 46,145
  • 13
  • 104
  • 123
  • 3
    Or `if (index in a)` would technically check for existence, though your `!== undefined` check will most likely suffice. –  Sep 28 '14 at 16:39
  • typeof a[index] !== 'undefined' should be more safe – Aubin Nov 17 '16 at 13:02
  • 3
    @Aubin Why? If `a` is not defined it will fail just as badly when trying to access `[index]`. – Andreas Louv Nov 17 '16 at 13:25
  • Please see http://stackoverflow.com/q/4725603/1624376 – Aubin Nov 18 '16 at 08:49
  • @Aubin That second comment there, you have the string `'undefined'` a rather than `undefined`. Makes a tremendous difference in output :O – Dan Gayle Jun 05 '17 at 18:05
  • @Dan: your 'undefined' could be overridden by a local variable inside a scope, even in ES5. Unlikely but possible. ;) `(function(undefined) { var a = [1, 2, 3], index = 2; if ( a[index] !== undefined ) { console.log('Index #' + index + '=' + a[index]); /* never triggered, cuz undefined is set to 3. typeof a[index] !== 'undefined' is better*/ } })(3)` – SammieFox Jul 30 '17 at 13:33
  • 7
    @SammieFox if a developer creates a function with `undefined` as its parameter name, he's worthy of being skinned alive regardless of programming language used, and worthy of being boiled in tar afterwards if he's coding in JS. FWIW, I wouldn't go with `void 0` instead of `undefined` just for that reason - it's not "defensive coding", it's "paranoid coding" since ES5. `void 0` is semantic noise, `undefined` is semantically correct. We should program with humans in mind, not computers, IMVHO. –  Mar 08 '18 at 03:46
  • 1
    @vaxquis Setting undefined as an (undefined) parameter-value, was a recommend coding-style for IIFE-patterns, to make sure that the undefined-parameter is really undefined and not already defined outside the scope (e.g. by third-party-scripts). But yeah, its unneccassary since ES5 with strict mode. https://books.google.de/books?id=IS0EAwAAQBAJ&lpg=PA32&ots=ZNZQx-edVE&dq=iife%20undefined&hl=de&pg=PA32 ---- https://toddmotto.com/what-function-window-document-undefined-iife-really-means/ – SammieFox Mar 10 '18 at 14:37
6

You should be able to use for(key in data)

var data = [];
data[1] = 'a';
data[3] = 'b';

for(var index in data) {
  console.log(index+":"+data[index]);
}
//Output:
// 1-a
// 3-b

Which will loop over each key item in data if the indexes aren't contiguous.

JasonM
  • 751
  • 6
  • 9
0

If what you are actually describing is an Object rather than an Array, but is array like in the fact that it has properties that are of uint32_t but does not have essential length property present. Then you could convert it to a real array like this. Browser compatibility wise this requires support of hasOwnProperty

Javascript

function toArray(arrayLike) {
    var array = [],
        i;

    for (i in arrayLike) {
        if (Object.prototype.hasOwnProperty.call(arrayLike, i) && i >= 0 && i <= 4294967295 && parseInt(i) === +i) {
            array[i] = arrayLike[i];
        }
    }

    return array;
}

var object = {
    1: "a",
    30: "b",
    50: "c",
},
array = toArray(object);

console.log(array);

Output

[1: "a", 30: "b", 50: "c"]`

On jsfiddle

Ok, now you have a sparsely populated array and want to use a for loop to do something.

Javascript

var array = [],
    length,
    i;

array[1] = "a";
array[30] = "b";
array[50] = "c";

length = array.length;
for (i = 0; i < length; i += 1) {
    if (Object.prototype.hasOwnProperty.call(array, i)) {
        console.log(i, array[i]);
    }
}

Ouput

1 "a"
30 "b"
50 "c"

On jsfiddle

Alternatively, you can use Array.prototype.forEach if your browser supports it, or the available shim as given on the MDN page that I linked, or es5_shim

Javascript

var array = [];

array[1] = "a";
array[30] = "b";
array[50] = "c";

array.forEach(function (element, index) {
    console.log(index, element);
});

Output

1 "a"
30 "b"
50 "c"

On jsfiddle

Xotic750
  • 22,914
  • 8
  • 57
  • 79