I am working on a function that returns an array containing all but the last element of the array located at the given key.
-If the array is empty, it should return an empty array.
-If the property at the given key is not an array, it return an empty array.
-If there is no property at the key, it should return an empty array.
Here's my codes:
function getAllButLastElementOfProperty(obj, key) {
var output = [];
if ( key in obj && Array.isArray(obj[key]) && obj[key].length !== 0)
{
for(var i = 0; i < obj[key].length; i++ ){
if(obj[key].length - 1){
output.push(obj[key][i]);
}
}
return output;
}
}
var obj = {
key: [1, 2, 3]
};
var output = getAllButLastElementOfProperty(obj, 'key');
console.log(output); // --> MUST RETURN [1,2]
My codes returns [1,2,3].
ANy idea what am I doing wrong?
if(obj[key].length - 1){always returns true (except for 0), so probably the mistake is there