Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Reducing an array into an object in Javascript

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading