-1

I have an array of strings with vehicle names.

a=['car', 'scooter', 'bike'];

I need to generate a array such that each object would have a property color:red in it

I used array.reduce for it. This is the code i have written

function getInitialMap(a) {
    const vehicleMap = [];
    return vehicles.reduce((_vehicleMap, type) => {
        _vehicleMap.concat({[type]: {color: red}});
        return _vehicleMap;
    }, vehicleMap);
}

what I got is:

_vehicleMap = [
    0:{car:{color:red}},
    1:{scooter:{color:red}},
    2:{bike:{color:red}}
]

what I required:

_vehicleMap = [
    car:{color:red},
    scooter:{color:red},
    bike:{color:red},
]

Can someone help in generating array with custom keys here

Cid
  • 14,968
  • 4
  • 30
  • 45
Gaurav Soni
  • 391
  • 1
  • 8
  • 26

2 Answers2

4

Map by definition is dictionary, it can't be an array. You also don't need reduce for this. Here is how I would do this

var a=['car', 'scooter', 'bike'];

var map = {};

a.forEach(function(v) {
  map[v] = {color: 'red'}
})

console.log(map)
Umair Abid
  • 1,453
  • 2
  • 18
  • 35
  • What's wrong with reduce? – Lorenz Merdian May 16 '18 at 11:41
  • nothing but its much more simpler with forEach its literally one line with es6 a.forEach(v => map[v] = {color: 'red'}) – Umair Abid May 16 '18 at 11:43
  • Sure it's kind of simpler. but it's not pure, hence you have to take care of possibly unintended side effects. – Lorenz Merdian May 16 '18 at 11:46
  • how do you mean? as in the difference between reduce and forEach in this case? – Umair Abid May 16 '18 at 11:51
  • I mean it in that way, that for the `forEach` approach, you need an extra variable declaration before the actual assignment. See this small discussion: https://stackoverflow.com/questions/37461580/array-foreach-vs-reduce – Lorenz Merdian May 16 '18 at 11:55
  • Still don't understand how it differs in implementation since you have to define the accumulator in reduce as well, however forEach mutates existing object but reduce doesn't so in that case it might be more helpful to use reduce – Umair Abid May 16 '18 at 12:02
4

If you want to do this with reduce: this is my solution:

const a = ['car', 'scooter', 'bike'];
const colored = a.reduce((agg, vehicle) => {
  agg[vehicle] = {color: 'red'};
  return agg;
}, {});
console.log(colored);
Lorenz Merdian
  • 722
  • 3
  • 14