Comparing Array Values With Object Keys

3.5k Views Asked by At

Write a function called "select".

Given an array and an object, "select" returns a new object whose properties are those in the given object AND whose keys are present in the given array.

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 }

My Solution:

function select(arr, obj) {
  for (var k in obj) {
    return arr.reduce((o, c) => {
      if (obj.hasOwnProperty(c)) {
        o[c] = obj[c]
      }
      return o
    }, {})
  }
}

var array = ['a', 'c', 'e'];

var object = {
  a: 1,
  b: 2,
  c: 3,
  d: 4
};

console.log(select(array, object));

My solution is working, but I have a feeling that I'm not using the best practices or most eloquent code. For example I'm using a for/in to search the object, but I never use the 'k' from for (var k in obj). Any tips would be appreciated.

3

There are 3 best solutions below

0
On

Iterate the array with Array#reduce and pluck all properties that exist on the object to a new object:

const arr = ['a', 'c', 'e'];
const obj = {
  a: 1,
  b: 2,
  c: 3,
  d: 4
};

const select = (arr, obj) => arr.reduce((r, prop) => {
    obj.hasOwnProperty(prop) && (r[prop] = obj[prop]);
    
    return r;
  }, {});

const output = select(arr, obj);
console.log(output); // --> { a: 1, c: 3 }

5
On

To get the intersection between the keys of the objects and the keys in the array, there are two approaches:

  • enumerate the object property keys and check which of them are also in the array
  • iterate the keys in the array and check which of them are also an object property

You don't have to do both loops. The first approach will be more efficient for small objects, the second one works well for large objects and small subsets as well.

function select(arr, obj) {
  let o = {};
  for (let k in obj)
    if (arr.includes(k))
      o[k] = obj[k];
  return o;
}

function select(arr, obj) {
  let o = {};
  for (let k of arr)
    if (k in obj)
      o[k] = obj[k];
  return o;
}

You can also use reduce instead of the for … of loop like you successfully did (I won't repeat that solution), but which of the two is easier to read and understand only you can decide.

1
On

You can use Object.assign() with reduce() and inside check if property exists in object.

var arr = ['a', 'c', 'e'];
var obj = { a: 1,b: 2,c: 3, d: 4};

let select = (arr, obj) => arr.reduce((r, e) => Object.assign(r, obj[e] ? {[e]: obj[e]} : null), {})

var output = select(arr, obj);
console.log(output); // --> { a: 1, c: 3 }