napruto
napruto

Reputation: 1

Returning first object in array of objects (JavaScript)

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?

Upvotes: 0

Views: 103

Answers (2)

DecPK
DecPK

Reputation: 25408

According to your object value, it should be string but you have used the wrong double quotes. It should be " " not “ ”.

You can also use single quote i.e ' '.Both are acceptable.

Everything else is working fine.

function firstElement(array) {
  if (array.length === 0) {
    return undefined;
  }
  if (array instanceof Array || typeof array === "string") {
    return array[0];
  }
}
const element1 = firstElement([1, 2, 3]); // 1
const element2 = firstElement([{ name: "Joseph" }, { name: "Ashley" }, { name: "Brandon" }]);

console.log( element1 );
console.log( element2 );

Upvotes: 2

Sandeep Chikhale
Sandeep Chikhale

Reputation: 1515

The object inside your array is incorrect, it should be a string that's why you are getting this issue. Just change “ to " in the object and your code will work as expected.

Try with the below array once.
[{ name : "Joseph" }, { name: "Ashley" }, { name: "Brandon" }]

function firstElement(array) {
      if (array.length === 0) {
        return undefined;
      }
      if (array instanceof Array || typeof array === "string") {
        return array[0];
      }
    }
   
    const first = firstElement([{ name: "Joseph" }, { name: "Ashley" }, { name: "Brandon" }]);
    console.log("first :", first);

Upvotes: 0

Related Questions