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?

asked Dec 5, 2017 at 3:16
1

1 Answer 1

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);
answered Dec 5, 2017 at 3:23
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.