I am trying to incorporate array method: reduce. Basically, what I am trying to accomplish here is to reduce the array below to an object where anything that matches obj's key value.
const arr = ['a', 'c', 'e'];
const obj = { a: 1, b: 2, c: 3, d: 4 };
let output = select(arr, obj);
console.log(output); // --> { a: 1, c: 3 }
My select method:
function select(arr, obj) {
let newObj = {};
for (let prop in obj) {
for (let i = 0; i < arr.length; i++) {
if (prop === arr[i]) {
newObj[prop] = obj[prop];
}
}
}
return newObj;
}
I set {} as initializer for arr.reduce as such if current value of array matches key of object then it would add to accumulator the key value, but I am receiving an error message from the console that if expression cannot return boolean.
Here is my attempt using .reduce():
function select(arr, obj) {
let result = arr.reduce(function(x, y) {
if (y in obj) {
x[y] = obj[y]
return x;
}
}, {})
return result;
}
Please advise.