2

I was given the assignment to create a function that, given an object and a key, returns an array containing all the elements of the array located at the given key that are less than 100. I came up with this:

function getElementsLessThan100AtProperty(obj, key) {
  var lessThan100 = [];
  var targetedKey = obj[key];
  if (targetedKey === undefined) {
    return [];
  }
  for (i = 0; i < targetedKey.length; i++) {
    if (targetedKey[i] < 100) {
      lessThan100.push(targetedKey[i]);
    }
  }
return lessThan100;
}

Now this works, but I am wondering why my original code didn't. I tried to loop over the array at the given property by writing the code below, but it didn't work. Why can't i do this? Also, would someone show me how to clean up this code to make it shorter?

for (i = 0; i <obj[key].length; i++) {
    if (obj[key[i]].length < 100) {
      lessThan100.push(obj[key[i]]);
    }
0

2 Answers 2

2

Because obj[key[i]] has to be obj[key][i], additionally you check if the length is smaller 100 which is probably not your intention.

The whole code could be written as:

 const getLessThanHundred = (obj, key) =>
   obj[key].filter(it => it < 100);
Sign up to request clarification or add additional context in comments.

2 Comments

Wow. I'm not familiar with that technique yet, but it does work. I am just beginning to learn to code and doing a bootcamp interview training program from hackreactor, so I am still very unfamiliar with javascript. Thank you for the help.
@sheridan glad to help :)
0

In your revised code you are checking if the length of the item in the array is less than 100, not if the value of the item is less than 100. You should be checking the value (ie < 100; not .length < 100)

3 Comments

Wow, thank you so much. Usually, when I make such an obvious mistake, I catch it after spending some time away from the problem and looking at it again with fresh eyes. I've been going back to this problem every day and I didn't catch that.
The function is supposed to return an empty array if the property obj[key] does not exist. Do I have to use an if statement for that or is there another way?
You can new up an empty array, and then push items into it if they exist. At the end, return the array. If nothing was added, you will return the empty array that you newed up.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.