0

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.

0

3 Answers 3

3

You must always return the accumulator. Here is how to use reduce

function select(arr, obj) {
    return arr.reduce(function (acc, key) {
        if (key in obj) acc[key] = obj[key];
        return acc;
    }, {});
}

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 }

Sign up to request clarification or add additional context in comments.

Comments

1

The accumulator should be returned in all the cases. I used an implementation using a filter for your reference:

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

function select (obj,arr){
    let newObj = Object.keys(obj).filter(key => arr.includes(key)).reduce((acc,key) => {
                    acc[key]=obj[key]
                    return acc 
                },{})
    return newObj
}
console.log(select(obj,arr)); 

Comments

0
function select(arr, obj) {
    return arr.reduce((acc, curr) => {
        if(obj[curr]) {
            acc[curr] = obj[curr];
        }
        return acc;
    }, {})
}

1 Comment

adding a verbal explanation to your answer can be very helpful

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.