Home > Software engineering >  Reducing an array into an object in Javascript
Reducing an array into an object in Javascript

Time:02-24

I want to turn the following object

const order = {
  apple: 5,
  banana: 5,
  orange: 5
};

into the following object, with each key being assigned its index in the object as its value

{
  apple: 0,
  banana: 1,
  orange: 2
}

This is the code I have but it's not working and I don't know why.

const indices = Object.keys(order).reduce(
    (previousValue, currentValue, currentIndex) =>
      (previousValue[currentValue] = currentIndex), {}
  );
TypeError: Cannot create property 'banana' on number '0'

What am I doing wrong here?

CodePudding user response:

Reducer is expected to return the accumulator:

const order = {
  apple: 5,
  banana: 5,
  orange: 5
};

const indices = Object.keys(order).reduce(
  (previousValue, currentValue, currentIndex) => {
    previousValue[currentValue] = currentIndex;
    return previousValue; // <-- this was missing in your attempt.
  }, {}
);

console.log(indices);

CodePudding user response:

const order = {
    apple: 5,
    banana: 5,
    orange: 5,
};

const mapByIndex = (obj) => {
    return Object.keys(obj).reduce((acc, curr, i) => {  
        return {
            ...acc,
            [curr]: i,
        };
    }, {});
};

console.log(mapByIndex(order)); // -> { apple: 0, banana: 1, orange: 2 }
  • Related