I've got this problem for precourse for a bootcamp:
// Assigns own enumerable properties of source object(s) to the destination
// object. Subsequent sources overwrite property assignments of previous sources.
// extend({ 'user': 'barney' }, { 'age': 40 }, { 'user': 'fred' });
// should return -> { 'user': 'fred', 'age': 40 }
// BONUS: solve with reduce
I've seen other questions on here solve this successfully using reduce (which I am still learning). However - I am trying to figure out why exactly the methods I used are being marked as incorrect by the testing site I'm given.
Here is a correct answer given on another question on here:
function extend(...destination) {
return destination.reduce(function(acc, val){
var keys = Object.keys(val),
key = null;
for(var keyIdx = 0, len = keys.length; keyIdx < len; keyIdx++){
key = keys[keyIdx];
acc[key] = val[key];
}
return acc;
});
Here are two of my answers that both got the same output - but were marked wrong. I assume this is because of object reference, but I am having trouble finding the exact problem.
function extend(...destination) {
const newObj = {};
destination.forEach(x => {
var keys = Object.keys(x);
for (let i = 0; i < keys.length; i++){
const key = keys[i];
newObj[key] = x[key];
}
});
return newObj;
and
function extend(...destination) {
const newObj = {};
destination.forEach(x => {
Object.assign(newObj, x);
});
return newObj;
Thanks in advance! Sorry if this is a dumb question - my first ask on here.