Joshua Rajandiran
Joshua Rajandiran

Reputation: 2928

Reduce not working as expected?

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?

Upvotes: 1

Views: 1374

Answers (5)

Adeel Imran
Adeel Imran

Reputation: 13966

You can achieve it by doing this

let array = ['a','b','c'];
return array.reduce((acc, currentValue, index) => {
    const key= index + 1;
    acc[key] = currentValue;
    return acc;
}, {});

Output will be like this

{
  "1": "a",
  "2": "b",
  "3": "c"
}

Upvotes: 0

Arup Rakshit
Arup Rakshit

Reputation: 118271

I'd do it with Array.reduce function, and Object computed property.

var sampleData = ['a', 'b', 'c'];
console.log(sampleData.reduce((mem, curr, index) => ({ ...mem,
  [index + 1]: curr
}), {}))

Upvotes: 0

Olivier Boissé
Olivier Boissé

Reputation: 18113

var arr = ['a','b','c'];
var result = arr.reduce((obj, val, index) => {
  obj[index + 1] = val;
  return obj; 
}, {});

console.log(result);

Upvotes: 0

Mark
Mark

Reputation: 92440

The problem is that result of this expression: iv[i+1]=cv is cv, which you then Object.assign to the accumulator. You could make it simpler with a simple assignment:

let sampleData = ['a','b','c'];
    
let convertArrToObjWithIndexProp = (arr) => 
    arr.reduce((iv,cv,i) => (iv[i+1] = cv, iv),{});

console.log(convertArrToObjWithIndexProp(sampleData));

Upvotes: 3

Steven Spungin
Steven Spungin

Reputation: 29109

Don't use Object.assign. Just update your object and return it.

let sampleData = ['a','b','c'];
    
    let convertArrToObjWithIndexProp = (arr) => {       
      return arr.reduce((iv,cv,i)=>{
         iv[i+1]=cv
         return iv
      },{});
    }
    console.log(convertArrToObjWithIndexProp(sampleData));

Upvotes: 1

Related Questions