Reputation:
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?
Upvotes: 1
Views: 3977
Reputation: 589
You could generalize your function by making it take an array as an argument and then calling getAllButLastElement(obj.key)
. This also returns an empty array if the object does not have the property key
.
This could then be implemented like this:
function getAllButLastElement(arr) {
if(!Array.isArray(arr))
return []; // Return an empty array
return arr.slice(0, -1);
}
let obj = {
'key': [ 1, 2, 3 ],
'empty': [ ]
};
console.log('obj.key:', getAllButLastElement(obj.key)); // Proper Array
console.log('obj.empty:', getAllButLastElement(obj.empty)); // Empty Array
console.log('obj.unknown:', getAllButLastElement(obj.unkown)); // Property does not exist
Passing a negative number to Array.prototype.slice
accesses the array from the end. In the snippet this means that we take everything from the first element up to the index arr.length - 1
. If we were to use arr.slice(-1)
this would only return the last element (still as an array of course) which is the exact opposite of what you want.
Upvotes: 1
Reputation: 73
Try this condition for your if
statement
if(i !== obj[key].length - 1){
output.push(obj[key][i]);
}
Upvotes: 0
Reputation: 92904
The optimized getAllButLastElementOfProperty
function version:
function getAllButLastElementOfProperty(obj, k) {
if (!obj.hasOwnProperty(k) || !Array.isArray(obj[k]) || obj[k].length === 0) {
return [];
}
return obj[k].slice(0, -1); // getting all but the last element of the array
}
var obj = { key: [1, 2, 3] },
output = getAllButLastElementOfProperty(obj, 'key');
console.log(output);
Upvotes: 2