1

I have a little problem with my Javascript code. Here is my question :

I want to write a function, who take in input a table of numbers. If numbers situated in even index, be returned as the way it is. But, if numbers situated in odd index, be return multiplied by his index.

For example :

Input :

[5, 10, 15, 20, 25, 30, 50, 100]

Return :

[5, 10, 15, 60, 25, 150, 50, 700]


So, my code :

function multiplyNum(numbers) {
  const multiply = numbers.map(function(number) {
      for (let i = 0; i < numbers.length; i++) {
        if (numbers[i] % 2 == 0) {
          return numbers
        }
        if (numbers[i] % 2 !== 0) {
          return numbers
        }
      });
    return multiplyNum
  }
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
From
  • 69
  • 1
  • 6
  • 2
    I'm not sure I see anywhere in your code where you're multiplying anything. I only see you using the mod operator. Am I just not seeing the multiplication? Also, you're comparing your values in two different ways. One way, you're doing a "double equals check" and the other, a "triple equals check". That is, you're doing an identity check in one and an equality check in another. Take a look at this -- https://stackoverflow.com/questions/359494/which-equals-operator-vs-should-be-used-in-javascript-comparisons Note: That's not gonna solve the problem here but consistency is good. – rudolph schmitz Oct 05 '18 at 19:52
  • You have unbalanced braces. And you should return `multiply`, not `multiplyNum`. – Barmar Oct 05 '18 at 20:25

2 Answers2

3

You don't need the for loop at all, you can get the index from the map and multiply the odd values:

function multiplyNum(numbers) {
  return numbers.map(function(number, index) {
    return index % 2 ? number * index : number;
  });
}

console.log(multiplyNum([5, 10, 15, 20, 25, 30, 50, 100]));
Zakaria Acharki
  • 66,747
  • 15
  • 75
  • 101
2

You could map with a conditional operator as a check.

var array = [5, 10, 15, 20, 25, 30, 50, 100],
    result = array.map((v, i) => i % 2 ? v * i : v);

console.log(result);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392