1

I want to run map() on a variable that might either be a single object or an array. However, I can't do this if the variable is an object as that throws an error.

I tried using the spread operator to make sure the variable turns into an array but apparently that doesn't work either:

// items can either be an object or an array of objects
renderedItems = [...items]
    .filter(item => !!item)
    .map((item, index) => _this.renderItem(item, index));

How can I make sure the variable I'm doing a filter() and map() on is an array? I heard Array.isArray isn't fully supported yet.

MarksCode
  • 8,074
  • 15
  • 64
  • 133

1 Answers1

2

You can use instanceof to check if the variable is an Array.

if(variable instanceof Array){
  //variable is an Array
} else {
  //variable is not an Array
}

var array = [1, 2, 3, 4, 5];
var str = "String";
function isArray(obj){
 return obj instanceof Array;
}
console.log("array is an Array: "+isArray(array));
console.log("str is an Array: " + isArray(str));

You can also use Array.isArray.

if(Array.isArray(variable)){
 //variable is an Array
} else {
  //variable is not an Array
}

var array = [1, 2, 3, 4, 5];
var str = "String";
function isArray(obj){
    return Array.isArray(obj);
}
console.log("array is an Array: "+isArray(array));
console.log("str is an Array: " + isArray(str));

You can check if the variable's constructor is equal to Array.

 var array = [1, 2, 3, 4, 5];
var str = "String";
function isArray(obj){
        return obj.constructor === Array;
 }
 console.log("array is an Array: "+isArray(array));
console.log("str is an Array: " + isArray(str));
Unmitigated
  • 76,500
  • 11
  • 62
  • 80