0

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:

  • If the array is empty, it should return an empty array.
  • If the array contains no elements are equal to 10, it should return an empty array.
  • If the property at the given key is not an array, it should return an empty array.
  • If there is no property at the key, it should return an empty array.

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?

bellwether
  • 71
  • 3

1 Answers1

1

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);
StackSlave
  • 10,613
  • 2
  • 18
  • 35