Creating new array with keys that match values of an array

Me again!

This time I’m supposed to create a function that takes 2 parameters (arr, obj ) that when invoked creates an object with only the properties pulled from the original obj that match the value of a given array.

function select(arr, obj) {
  newObj = {};
    for ( i = 0; i < arr.length; i++){
      if( obj.hasOwnProperty(i) ){
        newObj[i] = obj[i];
      }
    }
  return newObj;
}

Can anybody tell me what part of my code is wrong? Remember it returns a new object whose properties are those in the given object AND whose keys are present in the given array.

Notes:

  • If keys are present in the given array, but are not in the given object, it should ignore them.
  • It does not modify the passed in object.

Can you give an example of the call to the function and the expected output? If this is an FCC challenge, please post the url to the challenge or just specify the challenge name.

yes here it is

var arr = ['a', 'c', 'e'];
var obj = {
  a: 1,
  b: 2,
  c: 3,
  d: 4
};
var output = select(arr, obj);
console.log(output); // --> { a: 1, c: 3 }

Your select function code is changes the value of i during the for loop from 0 through arr.length. When you write:

if( obj.hasOwnProperty(i) ){

it will evaluate to false each iteration, because obj does not have property names of ‘0’, ‘1’, ‘2’, ‘3’. It has property names of ‘a’, ‘b’, ‘c’, ‘d’.

2 Likes

At long last :persevere: Thanks @RandellDawson!

function select(arr, obj) {
  newObj = {};
    for ( i = 0; i < arr.length; i++){
        if( obj.hasOwnProperty(arr[i]) ){
            let key = arr[i];
            newObj[key] = obj[key];
        }
    }
  return newObj;
}