Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

243
Visualizações
How to multiply array values without nested loops

Problem:

Given an array of integers, return a new array such that each element at index i of the new array is the product of all the numbers in the original array except the one at i.

For example:

  • if our input was [1, 2, 3, 4, 5], the expected output would be [120, 60, 40, 30, 24].

  • If our input was [3, 2, 1], the expected output would be [2, 3, 6].

Solution 1 (With Nested loops): I'm able to solve this by nested loops like below:

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

function output(items) {
const finalArray = [];
 for (let i = 0; i < items.length; i++) {
    let multipliedNum = 1;
    
    items.forEach((item, indx) => {
      if (i !== indx) {
        multipliedNum = multipliedNum * item;
      }
    });
         finalArray.push(multipliedNum)

    }
  return finalArray;

}

console.log(output(input))

I'm trying to find out another solution without nested loops inside output function? Any help or suggestion really appreciated.

about 4 years ago · Santiago Trujillo
3 Respostas
Responde à pergunta

0

If there are no zero values, you can loop through all the values once to get the product. Then just return the array where each the product is divided by each entry.

However, if there are zeros then there is a little more to be done to check how many there are. One zero is fine but more than 1 means that the value is zero for each entry.

const input = [1, 2, 3, 4, 5];
const input2 = [1, 2, 3, 4, 0];
const input3 = [1, 2, 3, 0, 0];

function output(items) {
  let zeroCount = 0;
  let totalProduct = 1;
  for (let i = 0; i < items.length; i++) {
    if (items[i] === 0) {
      if (++zeroCount > 1) break;
      continue;
    }
    totalProduct *= items[i];
  }

  if (zeroCount > 1) {
    // more than 1 zero -> all values are 0
    return new Array(items.length).fill(0);
  } else if (zeroCount === 1) {
    // only 1 zero -> only the value that is zero will be the totalProduct
    return items.map(item => item === 0 ? totalProduct : 0);
  }
  // no zero in array -> divide the totalProduct by each item
  return items.map(item => totalProduct / item);
}

console.log(output(input))
console.log(output(input2))
console.log(output(input3))

about 4 years ago · Santiago Trujillo Relatório

0

Based on what @Mike said in the comment here's the answer.

const input = [1, 2, 3, 4, 5];
const mulValues = input.reduce((acc, next) => acc * next);
const output = input.map(i => mulValues/i)
console.log(output)
about 4 years ago · Santiago Trujillo Relatório

0

you can do something like that (assuming array doesn't contain zero):

  • calculate product of all array elements
  • divide product by element at position [i] to get the desired output
const input = [1, 2, 3, 4, 5];

function output(items) {
const finalArray = [];
const multipliedNum=1;
 for (let i = 0; i < items.length; i++) {
     multipliedNum *= item[i];
    }
 for (let i = 0; i < items.length; i++) {
      finalArray.push(multipliedNum/item[i]);
   }
  return finalArray;
}

console.log(output(input))
about 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda