Home > OS >  Obtaining wrong element of an object javascript
Obtaining wrong element of an object javascript

Time:09-10

hey new to coding so please be gentle. I'm going through a testing website that supplies its own arguments and the the following code is returning the wrong element and I can't figure out why. Where am I going wrong? I'm trying to return the final element of the array contained within the object.

If the array contains one item, it should return that one item. If the array contains an empty string, it should return an empty string. If the object is empty, it should return an empty string.

This is the code I've got so far but it fails when being passed one of the arguments by the test returning r instead of up:

const movieData = {
  "studio": "Disney",
  "mainCharacter": "Carl Fredricksen",
  "films": ["Up"]
}

function lastElement(obj) {
  if (Object.keys(obj).length === 0)
    return "";
  else {
    let arr = Object.values(obj)[0];
    if (arr.length === 0)
      return "";
    else
      return arr[arr.length - 1]
  }
}

console.log(lastElement(movieData))

CodePudding user response:

You need to select the third object that is let arr = Object.values(obj)[2];

  • Related