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

Do anyone understand this reduce method problem Im having?

Do anyone understand why console.log(posArr) is printing [1,2,3] and not [0,1,2]. Im trying to push to nOfPos all the index positions of my array 🙂

function combinations(x) {
  let arr = x.toString().split('');
  console.log(arr)

  let nOfPos = [];
  let posArr = arr.map(x => nOfPos.push(arr.indexOf(arr[x])));
  let mult = posArr.reduce((acum, item) => acum * item);

  console.log(posArr);
  console.log(mult);
}

combinations(123)

>Solution :

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

The problem is due to two errors in your code. Firstly push() returns the new length of the array, so that’s why the mapped output contains the incremental 1,2,3....

Secondly, you need to search for x within arr, so you only need to pass x to indexOf().

With those issues corrected the code works:

function combinations(x) {
  let arr = x.toString().split('');
  let posArr = arr.map(x => arr.indexOf(x));
  let mult = posArr.reduce((acum, item) => acum * item);

  console.log(posArr);
  console.log(mult);
}

combinations(123)

That being said, the purpose of posArr is a little redundant; it will always be an array of incremental values, up to the length of the string -1.

In addition, mult is redundant too as it will always be 0, as you are multiplying by 0.

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