DEV Community

Discussion on: Daily Coding Problem #2

Collapse
 
lgmf profile image
Luiz Guilherme

stackblitz.com/edit/js-xqagwj

const appDiv = document.getElementById('app');

const arr = [1, 2, 3, 4, 5];

const result = arr.map(
  (item) => 
    arr
      .filter(n => n !== item )
      .reduce((acc,current) => acc * current , 1)
);


appDiv.innerHTML = `<h1>RESULT: ${result.toString()}</h1>`;
Collapse
 
hasheendeberry profile image
Hasheen DeBerry

I did something very similar to this. I realised quickly that if any of the numbers in the array are repeated, the totals don’t come out right. I had to explicitly remove the element from the input array and then use the reduce function to calculate the product.
HTH

Collapse
 
gungrave223 profile image
Gungrave223 • Edited
const array = [1, 2, 3, 4, 5];

const updated = array.map((ignored, currentIndex) =>
  array.reduce((accum, value, index) => {
    if (currentIndex === index) return accum
    return accum * value;
  }, 1));