user7435957
user7435957

Reputation:

Return Element Array from an object key

Given an object and a key, I created a function that returns an array containing all the elements of the array located at the given key that are equal to 10.

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

function getElementsThatEqual10AtProperty(obj, key) {
  for(var prop in obj){
    if(obj[prop] === 10){
      return obj[key];
    }
  }
}

var obj = {
  key: [1000, 10, 50, 10]
};

var output = getElementsThatEqual10AtProperty(obj, 'key');
console.log(output); // --> IT MUST RETURN [10, 10]

Any idea what am I doing wrong?

Upvotes: 0

Views: 1536

Answers (7)

Matt D. Webb
Matt D. Webb

Reputation: 3314

This can be achieved by using filter.

The filter() method creates a new array with all elements that pass the test implemented by the provided function.

My solution below I have used ES6 arrow syntax to be more concise. You could also call .filter() directly on the array and explicitly provide the predicate (item === 10) instead of creating the function for this to be dynamically provided.

const myArr = [10,100,10,1];

const filterBy = (arr, key) => arr.filter(item => item === key);

filterBy(myArr, 10); // returns [10, 10]

Note: if the predicate provided to the filter is not met (in this case, the value 10 is not found), an empty array will be returned.

Upvotes: 0

Văn Quyết
Văn Quyết

Reputation: 2526

With your case, you can use method reduce of the Array. Inside your function:

 return obj[key].reduce(function (result, value) {
      if (value === 10) result.push(value)
 }, []);

MSDN reference: .reduce()

Upvotes: 0

Michael Seltene
Michael Seltene

Reputation: 591

There is shorter way. One could use .map & .filter please see below.

var obj = {
   key: [1000, 10, 50, 10]
};

//To get the key
var output = obj.key.map((obj,i) => obj === 10 ? obj : '').filter(String);

//To get the index
var index = obj.key.map((obj,i) => obj === 10 ? i : '').filter(String);


//log output || index
console.log(output);

Upvotes: 0

Jeppsen
Jeppsen

Reputation: 497

Maybe something like this will help you in the right direction?

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

var obj = {
  key: [1000, 10, 50, 10]
};

var output = getElementsThatEqual10AtProperty(obj);
console.log(output);

Upvotes: 0

user2340824
user2340824

Reputation: 2152

In your code, you are iterating over all the properties in the Object.

for(var prop in obj)

so prop will be, in your 'key' in the first iteration. Then you ask does obj['key'] === 10.

This isn't the check you want to make, as this is basically [1000, 10, 50, 10] === 10

You could then Filter the array, looking for all items which match you condition, which is Does it equal to 10?

return obj['key'].filter(function(item) {
    return item === 10;
});

You can go further, as you know the Key you are looking for, as you pass it into your function, so you don't have to iterate over your Object, you can go straight to it:

obj[key]

But, as you said, you want to return an empty array if it doesn't match, so you can use:

var array = (obj[key] || [])

Which basically means, if obj[key] doesn't exist, then just use [].

Combining the whole thing looks like:

function foobar(object, key) {  
  return (object[key] || []).filter(function(item) {
    return item === 10;
  });
}

var object = {
  unique: [1, 10, 100, 10],
  nothing: [1,2,3,4,5]
}

console.log(foobar(object, 'unique'));  // returns [10, 10]
console.log(foobar(object, 'asgasgag')); // returns [] 
console.log(foobar(object, 'nothing')); // returns []

Upvotes: 1

Derlin
Derlin

Reputation: 9891

If I understand correctly, you want to check if the property key of obj is an array and if so, return all elements equal to 10.

Since you already have the name of the property, no need to iterate. Just access the key property directly, and check if it is of type Array. Then, you need to filter the array.

Here is an example of code (not the best one, but for learning purpose):

function getElementsThatEqual10AtProperty(obj, key) {
  if(obj[key] instanceof Array){ 
     // the key property is an array
     return obj[key].filter(function(v){ return v == 10;})
  }  
  // not an array
  return [];
}

Upvotes: 0

charlietfl
charlietfl

Reputation: 171679

obj['key'] is an array ... so it can never equal 10. You need to filter that array also.

Can use Array#filter() for this

function getElementsThatEqual10AtProperty(obj, key) {
   var arr = obj[key] || [];
    return arr.filter(function(val){
        return val === 10;
    });
}

var obj = {
  key: [1000, 10, 50, 10]
};

var output = getElementsThatEqual10AtProperty(obj, 'key');
console.log(output); // --> IT MUST RETURN [10, 10]

Upvotes: 1

Related Questions