bellwether
bellwether

Reputation: 81

Difference between normal for loop and for...in?

I'm trying to write a function to fulfil the following requirements:

Given an object and a key, "getElementsThatEqual10AtProperty" returns an array containing all the elements of the array located at the given key that are equal to ten.

Notes:

Example:

var obj = {
  key: [1000, 10, 50, 10]
};
var output = getElementsThatEqual10AtProperty(obj, 'key');
console.log(output); // --> [10, 10]

Approach #1 (fails the final point *If there is no property at the key, it should return an empty array.):

function getElementsThatEqual10AtProperty(obj, key) {

  var output = [];
  for (var i = 0; i < obj[key].length; i++) {
    if (obj[key][i] === 10) {
      output.push(obj[key][i]);
    }
  }
 return output;
}

Approach #2 passes all:

function getElementsThatEqual10AtProperty(obj, key) {

  var output = [];
  for (let i in obj[key]) {
    if (obj[key][i] === 10) {
      output.push(obj[key][i]);
    }
  }
  return output;
}

From my understanding, both loops and the subsequent conditional push has the same logic. Why does one work over the other?

Upvotes: 0

Views: 62

Answers (1)

StackSlave
StackSlave

Reputation: 10617

You're making this more complicated than it needs to be. I would just do this:

function getSameVals(yourArray, val){
  var a = [];
  for(var i=0,l=yourArray.length; i<l; i++){
    if(yourArray[i] === val){
      a.push(val);
    }
  }
  return a;
}
var ten = getSameVals(obj.key, 10);
console.log(ten);

Upvotes: 1

Related Questions