How do I loop over an array at a given key on an object?

Viewed 42

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]]);
    }
2 Answers

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);

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)

Related