How to check if an array index exists or not in javascript?
JavascriptTitaniumTitanium MobileJavascript Problem Overview
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.
Javascript Solutions
Solution 1 - Javascript
Use typeof arrayName[index] === 'undefined'
i.e.
if(typeof arrayName[index] === 'undefined') {
// does not exist
}
else {
// does exist
}
Solution 2 - Javascript
var myArray = ["Banana", "Orange", "Apple", "Mango"];
if (myArray.indexOf(searchTerm) === -1) {
console.log("element doesn't exist");
}
else {
console.log("element found");
}
Solution 3 - Javascript
These days I would take advantage of ecmascript and use it like that
return myArr?.[index]
Solution 4 - Javascript
Someone please correct me if i'm wrong, but AFAIK the following is true:
- Arrays are really just Objects under the hood of JS
- Thus, they have the prototype method
hasOwnProperty
"inherited" fromObject
- 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
Solution 5 - Javascript
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!
}
Solution 6 - Javascript
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).
Solution 7 - Javascript
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')
Solution 8 - Javascript
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;
}
});
Solution 9 - Javascript
var demoArray = ['A','B','C','D'];
var ArrayIndexValue = 2;
if(ArrayIndexValue in demoArray){
//Array index exists
}else{
//Array Index does not Exists
}
Solution 10 - Javascript
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
}
Solution 11 - Javascript
var fruits = ["Banana", "Orange", "Apple", "Mango"];
if(fruits.indexOf("Banana") == -1){
console.log('item not exist')
} else {
console.log('item exist')
}
Solution 12 - Javascript
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!")
}
Solution 13 - Javascript
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.
Solution 14 - Javascript
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');
}
}
Solution 15 - Javascript
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")
Solution 16 - Javascript
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
Solution 17 - Javascript
const arr = []
typeof arr[0] // "undefined"
arr[0] // undefined
If boolean expression
typeof arr[0] !== typeof undefined
is true then 0 is contained in arr
Solution 18 - Javascript
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
Solution 19 - Javascript
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');
}
Solution 20 - Javascript
(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
Solution 21 - Javascript
if(typeof arrayName[index] == undefined) {
console.log("Doesn't exist")
}
else {
console.log("does exist")
}