Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing Array Values With Object Keys

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.

like image 419
jhazelton1 Avatar asked Jun 04 '26 06:06

jhazelton1


2 Answers

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 }
like image 193
Nenad Vracar Avatar answered Jun 06 '26 20:06

Nenad Vracar


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.

like image 37
Bergi Avatar answered Jun 06 '26 20:06

Bergi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!