Problem to multiply the values ​​of my Javascript array

Question:

Good afternoon I am doing several practice exercises that they gave me during the year in college and one cost me some work and even so I do not think it is the most optimal way to solve it, that is why I ask you to help me find another type from solution. In the problem the data they give me are the following:

  • an array of numbers [6,2,8,5,1]
  • a number n = 10;

What it asks me is to show in the console one or more combinations of two numbers from the array that multiplied by each other are equal to n

  • It is an exercise that during the year had brought me problems and today I solved it in the following way [The problem that repeats the combinations that I found but in a different order therefore duplicates them for me example: 7 + 3 = n and then the order changes : 3 + 7 = n], that's why I'm looking for a way to simplify this exercise:
function operacion() {
  let numbers = [2, 6, 3, 4, 7, 5];
  n = 10;
  numbers.forEach((value) => {
    const valor = value;
    for (element in numbers) {
      if (valor !== numbers[element] && valor * numbers[element] == n) {
        console.log(valor + " * " + numbers[element] + " = " + "10")
      } else {
        null
      }
    }
  });
}

operacion();

Answer:

I recomend you:

Take advantage of the fact that you are using a function, use input parameters

Instead of writing fixed values ​​like:

let numbers = [2, 6, 3, 4, 7, 5];
n = 10;

Within your function, use parameters, in this case you have an array and a number, this will allow you to make your code portable and be able to reuse it.

function operacion(miArray, n)

Iterators

You can iterate with a for or with a forEach Why do you use different methods? Are there any that allow you to get any advantage?

You don't need to reassign variable

numbers.forEach((value) => {
    const valor = value;

You already have the value of value in the following code ( scope ), you don't need to create a new variable to store this value.

Don't compare values, compare indices

valor * numbers[element] == n

With an array = [5,5] and an n = 25 you would not have any results because you are comparing if the values ​​are equal and you would be discarding a solution.

Use literal templates

They allow you to format the strings in a more dynamic way: documentation .

Taking all this into account

I offer you this solution, in which the variables have descriptive names, use two forEach and in order not to return to past solutions the comparison of the indices is indiceA>=indiceB , this will avoid duplicates.

 function operacion(miArray, n) { miArray.forEach((valorA, indiceA) => { miArray.forEach((valorB, indiceB) => { if(indiceA>=indiceB && valorA*valorB===n){ console.log(`${valorA}*${valorB} = ${n}`); } }); }); } operacion([2, 6, 3, 4, 7, 5],10);
Scroll to Top