I am creating a function that:
- returns an array containing all the odd length word elements of the array located at the given key.
- If the array is empty, it should return an empty array.
- If it contains no odd length elements, it should return an empty array.
- If the property at the given key is not an array, it should return an empty array.
- If there is no property at the given key, it should return an empty array.
Here's my solution which works on some part so far:
function getOddLengthWordsAtProperty(obj, key) {
var output = [];
for(var i = 0; i < obj.key.length; i++){
if (key in obj){
if (Array.isArray(obj[key])){
if(obj[key].length){
if(obj.key[i].split("").length % 2 !== 0){
output.push(obj.key[i]);
}
}
}
}else{
return [];
}
}
return output;
}
var obj = {
key: ['It', 'has', 'some', 'words']
};
var output = getOddLengthWordsAtProperty(obj, 'key');
console.log(output); // --> ['has', 'words']
The problem here is that my codes return:
TypeError: Cannot read property 'length' of undefined