How to check if an array index exists or not in javascript?
Asked Answered
F

20

294

I am working with Titanium, my code looks like this:

var currentData = new Array();
if(currentData[index]!==""||currentData[index]!==null||currentData[index]!=='null')
{
    Ti.API.info("is exists  " + currentData[index]);
    return true;
}
else
{   
    return false;
}

I am passing an index to the currentData array. I still can't detect a non-existing index using the above code.

Faison answered 28/10, 2012 at 9:56 Comment(2)
Your logic is wrong. You need conjunctions (&&) between the individual conditions.Intravenous
Try these checks - https://mcmap.net/q/102066/-check-for-existence-of-key-in-multidimensional-array-in-javascriptHindquarter
H
528

Use typeof arrayName[index] === 'undefined'

i.e.

if(typeof arrayName[index] === 'undefined') {
    // does not exist
}
else {
    // does exist
}
Hayes answered 28/10, 2012 at 9:58 Comment(7)
+1, nice. You can also use if(arrayName[index] === 'undefined') as a shortcutHoboken
@Hoboken no, you cannot! But you can use if(arrayName[index] === undefined).Sheridansherie
this fails, if the item is there, but it's value is undefined; use this answer instead -> #1098540Compander
as @Compander said, there is more explanation here, you should be aware on.Mistral
What if you have a 2D array? (typeof tree[4][4] === 'undefined') If [4][4] does not exist, then you will get an error that it's an undefined object.Delacourt
for if(arrayName[index] === undefined) you may use even shorter one which is if(!arrayName[index])Bonis
@ParkJongBum That will only work if they understand "falsy" in JavaScript and if the array contains no falsy values. For example, if a[0] exists and is an empty string (or 0 or null or other falsy value), !a[0] will return true (saying the element does not exist) instead of false: a = ['']; if (a[0] === undefined) { console.log('not-exist') } else { console.log('exists') } ; if (!a[0]) { console.log('not-exist') } else { console.log('exists') } Carleton
G
91
var myArray = ["Banana", "Orange", "Apple", "Mango"];

if (myArray.indexOf(searchTerm) === -1) {
  console.log("element doesn't exist");
}
else {
  console.log("element found");
}
Griffiths answered 12/9, 2013 at 17:35 Comment(3)
Unfortunately, this one doesn't work in IE 7 and below.Bentwood
This in my opinion is the best answer, by now IE 7 is not mainteined any more so it's not a problem. Although I will suggest to use the triple equals if(myArray.indexOf(searchTerm) === -1)Instigate
The OP was looking to see if the given index number exists. This is checking if a given value exists.Carleton
D
59

These days I would take advantage of ecmascript and use it like that

return myArr?.[index]
Darkling answered 5/3, 2021 at 11:59 Comment(4)
@dsi you are allways free to check it in console. Anyway it should. Idea is exactly to save you from error on that case.Darkling
let date = string.match(/Date: (.*)/)?.[1] > SyntaxError: Unexpected token '.'Tameratamerlane
Wow this is brilliant, tested all the cases and working really well.Hackle
What would return if myArr[index] does not exists?Roncesvalles
E
33

This is exactly what the in operator is for. Use it like this:

if (index in currentData) 
{ 
    Ti.API.info(index + " exists: " + currentData[index]);
}

The accepted answer is wrong, it will give a false negative if the value at index is undefined:

const currentData = ['a', undefined], index = 1;

if (index in currentData) {
  console.info('exists');
}
// ...vs...
if (typeof currentData[index] !== 'undefined') {
  console.info('exists');
} else {
  console.info('does not exist'); // incorrect!
}
Escolar answered 1/10, 2019 at 13:49 Comment(3)
Only works on numeric index since it searches if the property exists on the object. Examaple let colors = new Array("green", "blue", "yellow"); "yellow" in colors >> falseSheree
@PolRué That's by design, the in operator checks if the index exists (has an associated value as opposed to being a hole). If you want to check the membership of an element, I suggest using the Set type and its .has methodEscolar
Yes, I reached that conlusion too. In my case .has worked wellSheree
A
22

Someone please correct me if i'm wrong, but AFAIK the following is true:

  1. Arrays are really just Objects under the hood of JS
  2. Thus, they have the prototype method hasOwnProperty "inherited" from Object
  3. in my testing, hasOwnProperty can check if anything exists at an array index.

So, as long as the above is true, you can simply:

const arrayHasIndex = (array, index) => Array.isArray(array) && array.hasOwnProperty(index);

usage:

arrayHasIndex([1,2,3,4],4); outputs: false

arrayHasIndex([1,2,3,4],2); outputs: true

Anteversion answered 3/4, 2019 at 20:21 Comment(4)
This also works for undefined and null values in the array, which none of the other answers here do.Grumble
Verified from MDN: "If an Object is an Array, hasOwnProperty method can check whether an index exists." developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…Omari
Also, hasOwnProperty won't return true for inherited properties like __proto__, this should be the answer.Promisee
This also works for arrays containing zeros and other falsy values +1.Capacitor
P
6

This also works fine, testing by type using === against undefined.

if (array[index] === undefined){ return } // True

Test:

const fruits = ["Banana", "Orange", "Apple", "Mango"];

if (fruits["Cherry"] === undefined){
  console.log("There isn't any cherry in the fruits basket :(")
}

Or similarly:

const fruits = ["Banana", "Orange", "Apple", "Mango"];

if (!fruits["Cherry"]){
  console.log("There isn't any cherry in the fruits basket :(")
}

// No errors: 
if (fruits["Cherry"]){
  console.log("There is some cherry in there!")
}
Position answered 2/2, 2020 at 8:46 Comment(1)
for cases where undefined is not expected to be a valid element in the array, i will prefer this version, as it is the most efficient way possible. only grab for my answer if undefined is a valid element in your arrays, and you really need to check if anything is existing at that index or not(to avoid useless set of item at that index). this probably wont apply for you if you are not doing embedded development where clock cycles > everything else.Anteversion
D
4

I had to wrap techfoobar's answer in a try..catch block, like so:

try {
  if(typeof arrayName[index] == 'undefined') {
    // does not exist
  }
  else {
  // does exist
  }
} 
catch (error){ /* ignore */ }

...that's how it worked in chrome, anyway (otherwise, the code stopped with an error).

Doerr answered 9/8, 2013 at 14:0 Comment(1)
This should only have "broken" with an error if the variable arrayName itself (or index) did not exist. Simply accessing an undefined array element should not have resulted in an "error"?Infectious
T
4
var demoArray = ['A','B','C','D'];
var ArrayIndexValue = 2;
if(ArrayIndexValue in demoArray){
   //Array index exists
}else{
   //Array Index does not Exists
}
Tun answered 31/10, 2018 at 16:17 Comment(1)
What are you expecting ..what is the question actually?Benco
S
3

If elements of array are also simple objects or arrays, you can use some function:

// search object
var element = { item:'book', title:'javasrcipt'};

[{ item:'handbook', title:'c++'}, { item:'book', title:'javasrcipt'}].some(function(el){
    if( el.item === element.item && el.title === element.title ){
        return true; 
     } 
});

[['handbook', 'c++'], ['book', 'javasrcipt']].some(function(el){
    if(el[0] == element.item && el[1] == element.title){
        return true;
    }
});
Stewardson answered 22/1, 2015 at 12:42 Comment(1)
some is the modernest way around here. It also can even become a one-liner like myArray.some(el => el.item === element.item && el.title === element.title)Claudieclaudina
D
3

Consider the array a:

var a ={'name1':1, 'name2':2}

If you want to check if 'name1' exists in a, simply test it with in:

if('name1' in a){
console.log('name1 exists in a')
}else
console.log('name1 is not in a')
Delinquency answered 16/8, 2015 at 4:43 Comment(3)
"var a" is not an array object in your case, but a regular object. Should be var a = [ ... ]. I think this is what author needed.Noyade
This is how to check for the existence of a key in an object, not the presence of an index in an array.Ackerley
The in operator seems to work with arrays too. Like 2 in [5, 6, 7, 8, 9, 10] is true, but 6 in [5, 6, 7, 8, 9, 10] is false. Just change your answer to array to be relevant.Hydrous
B
2

If you are looking for some thing like this.

Here is the following snippetr

var demoArray = ['A','B','C','D'];
var ArrayIndexValue = 2;
if(demoArray.includes(ArrayIndexValue)){
alert("value exists");
   //Array index exists
}else{
alert("does not exist");
   //Array Index does not Exists
}
Benco answered 31/10, 2018 at 19:38 Comment(2)
This is the solution I am going to use im my project today. I have no idea why there were downvotes - this works best for my use case, which is server-side node.js / express. Thank youMemorialize
@Memorialize because that is not what this question is for. we've long had the ability prior to Array.includes to check if a value is an array, like demoArray.indexOf(ArrayIndexValue) !== -1. this question is about checking whether the index exists in the array, which is an entirely different problemAnteversion
S
2

One line validation. The simplest way.

return !!currentData[index];

Outputs

var testArray = ["a","b","c"]

testArray[5]; //output => undefined
testArray[1]; //output => "b"

!!testArray[5]; //output => false
!!testArray[1]; //output => true
Sheik answered 1/8, 2021 at 13:29 Comment(3)
It is of course okay, however, when everything become highly nested (harder to read), the way you shown is adding an extra level of complexity for readers. Even for experienced js coders, getting the logic in one read is difficult.Position
testArray = [0, 0, 0] will result in false for every index even though they are given.Fieldfare
This returns incorrect results if your array contains zero.Vocalize
E
1

If you use underscore.js then these type of null and undefined check are hidden by the library.

So your code will look like this -

var currentData = new Array();

if (_.isEmpty(currentData)) return false;

Ti.API.info("is exists  " + currentData[index]);

return true;

It looks much more readable now.

Economist answered 29/5, 2014 at 19:47 Comment(1)
Even if your answer is right, I would just think twice for this. Your code would become underscore.js dependent only for checking an empty value. Just do a simple wrapper function isset(v) { return (typeof v !== 'undefined'); }Madagascar
B
1

This way is easiest one in my opinion.

var nameList = new Array('item1','item2','item3','item4');

// Using for loop to loop through each item to check if item exist.

for (var i = 0; i < nameList.length; i++) {
if (nameList[i] === 'item1') 
{   
   alert('Value exist');
}else{
   alert('Value doesn\'t exist');
}

And Maybe Another way to do it is.

nameList.forEach(function(ItemList)
 {
   if(ItemList.name == 'item1')
        {
          alert('Item Exist');
        }
 }
Banded answered 31/12, 2015 at 23:7 Comment(0)
T
1

Simple way to check item exist or not

Array.prototype.contains = function(obj) {
    var i = this.length;
    while (i--)
       if (this[i] == obj)
       return true;
    return false;
}

var myArray= ["Banana", "Orange", "Apple", "Mango"];

myArray.contains("Apple")
Tonitonia answered 23/11, 2016 at 14:21 Comment(1)
horribly inefficient. what if I set myArray[1000000] = 'Pear' then your function will take forever.Emanation
L
1

var fruits = ["Banana", "Orange", "Apple", "Mango"];
if(fruits.indexOf("Banana") == -1){
    console.log('item not exist')
} else {
	console.log('item exist')
}
Luxuriance answered 27/5, 2019 at 6:54 Comment(0)
C
0

you can simply use this:

var tmp = ['a', 'b'];
index = 3 ;
if( tmp[index]){
    console.log(tmp[index] + '\n');
}else{
    console.log(' does not exist');
}
Chrysoberyl answered 21/7, 2015 at 15:23 Comment(1)
wrong. what if tmp = [0,0,0,0] then tmp[3] should existEmanation
G
0
(typeof files[1] === undefined)?
            this.props.upload({file: files}):
            this.props.postMultipleUpload({file: files widgetIndex: 0, id})

Check if the second item in the array is undefined using the typeof and checking for undefined

Geopolitics answered 14/10, 2018 at 23:57 Comment(0)
R
0
if(typeof arrayName[index] == undefined) {
    console.log("Doesn't exist")
}
else {
console.log("does exist")
}
Rascal answered 21/7, 2021 at 7:58 Comment(0)
P
-1

When trying to find out if an array index exists in JS, the easiest and shortest way to do it is through double negation.

let a = [];
a[1] = 'foo';
console.log(!!a[0])   // false
console.log(!!a[1])   // true
Profant answered 30/9, 2019 at 13:56 Comment(2)
what about a[1] = false? 0? ''?Unearthly
This returns incorrect results if your array contains zero.Vocalize

© 2022 - 2024 — McMap. All rights reserved.