I'm currently trying to convert an array into an object with the array index as the property of the created object.
Example Array: ['a','b','c']
Expected Object result: {'1':'a','2':'b','3':'c'}
My code is below, it worked when I used map method but when I use the reduce method instead it comes out weird way:
let sampleData = ['a','b','c'];
let convertArrToObjWithIndexProp = (arr) => {
/*let res = {};
arr.map((v,k)=> {
res[k+1]=v;
})
return res;*/
//--> this outputs {'1':'a','2':'b','3':'c'}
return arr.reduce((iv,cv,i)=>{
return Object.assign(iv,iv[i+1]=cv);
},{});
//--> this outputs instead {'0':'c','1':'a','2':'b','3':'c'}
}
console.log(convertArrToObjWithIndexProp(sampleData));
Can someone explain to me why its coming out like that?
Also is using reduce better than using map?