I'm having trouble with this function. I'm supposed to return the first element of an array, which I'm able to do with arrays of numbers or a string.
function firstElement(array) {
if (array.length === 0) {
return undefined;
}
if (array instanceof Array || typeof(array) === "string") {
return array[0];
}
}
firstElement([1, 2, 3]); // 1
firstElement([{ name: “Joseph” }, { name: “Ashley” }, { name: “Brandon” }]); // {name: “Joseph”}
However, when it comes to an array of objects, I'm not quite sure how I'm supposed to return the whole object ({name: "Joseph"}). At first, I tried doing it the same way I would return the first number in a number array, but I was thrown a SyntaxError. It seemed as simple as that but I'm just completely stuck now. I want it to be able to work for any {key: value} object and not just specifically names.
Can anyone see where I am wrong?
lengthcheck should not take place before the type check. Looking additionally at the possible return values, the implementation offirstElementcould be much simplified based on the usage ofArray.fromand making sure that the passed argument is neither anullnor anundefinedvalue ...function firstElement(value) { return Array.from(value != null ? value : [])[0]; }... or in another variant something like ...const firstElement = value => Array.from(value ?? [])[0];