Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

can't figure out how to use reduce properly

Tags:

javascript

My goal is:

var arr = [{name: 'Alex'},{name: 'Mia'},{name: 'David'}];
bz(arr,'areWeAwesome','shuAr')

This should change arr to:

[{name: 'Alex', areWeAwesome: 'shuAr'},{name: 'Mia', areWeAwesome: 'shuAr'},{name: 'David', areWeAwesome: 'shuAr'}];

And I actually know how to do this:

function bz(zarr,zkey,zval) {
    for(var i in zarr) {
        zarr[i][zkey] = zval;
    }
}

But I can't figure it out how to implement this with reduce... I just don't see it. I tried many variations, the last one is this:

function bzz(zarr,zkey,zval) {
    return zarr.reduce(function(acc,val){
        return acc[val[zkey] = zval]
    },[{}]);
}

I read about reduce in the MDN documentation, but it didn't help... I just can't get it... would appreciate if you could help me with this

like image 272
danedidug Avatar asked Nov 25 '25 20:11

danedidug


1 Answers

With Array#reduce and Array#concat for a new object with the wanted key/value pair.

function bz(array, key, value) {
    return array.reduce((r, o) => r.concat(Object.assign({}, o, { [key]: value })), []);
}

var arr = [{name: 'Alex'},{name: 'Mia'},{name: 'David'}];
console.log(bz(arr,'areWeAwesome','shuAr'));

With Array#map, which is preferable, because it returns an array with a value for each item of the given array.

function bz(array, key, value) {
    return array.map(o => Object.assign({}, o, { [key]: value }));
}

var arr = [{name: 'Alex'},{name: 'Mia'},{name: 'David'}];
console.log(bz(arr,'areWeAwesome','shuAr'));
like image 139
Nina Scholz Avatar answered Nov 27 '25 09:11

Nina Scholz



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!