Javascript-форум (https://javascript.ru/forum/)
-   Общие вопросы Javascript (https://javascript.ru/forum/misc/)
-   -   Подскажите что не так (https://javascript.ru/forum/misc/83970-podskazhite-chto-ne-tak.html)

Mr_Po 30.04.2022 14:36

Подскажите что не так
 
Всем снова здравствуйте, очередная задача по js, и нужна помощь с решением:
Реализуй функцию getArrayProduct, которая получает массив чисел numbers и возвращает массив такого же размера, где numbers[i] равно произведению всех элементов массива справа и слева от этого элемента.

Примечания:

Начальный массив содержит не менее 2 элементов
Массив содержит только положительные числа
Числа могут повторяться
Примеры:

productArray([1,5,2]) === [10,2,5]

The first element 10 is the product of all array's elements except the first element 1
The second element 2 is the product of all array's elements except the second element 5
The third element 5 is the product of all array's elements except the third element 2
getArrayProduct([12,20]) === [20,12]

The first element in array 20 is the product of all array's elements except the first element
The second element 12 is the product of all array's elements except the second element.

Вот то до чего я додумался но что-то не так
function getArrayProduct(numbers) {
  let num = 1;
  const result = [];

  for (let i = 0; i < numbers.length; i++) {
    num *= numbers[i];
  }

  return result;
}

Nexus 30.04.2022 14:58

function getArrayProduct(numbers) {
    const numbersProduct = numbers.reduce((res, num) => res * num, 1);
    
    return numbers.map(num => numbersProduct / num);
}

console.log(
    getArrayProduct([1,5,2]).toString() === [10,2,5].toString()
);// true

рони 30.04.2022 15:03

Mr_Po,
нужен цикл в цикле, первый по всем элементам, второй по всем кроме текущего.

Mr_Po 03.05.2022 14:25

Спасибо большое, разобрался немного:thanks:


Часовой пояс GMT +3, время: 18:07.