简体   繁体   中英

How to use Modulo inside of a forEach loop using arrow function?

I just do a coding challenge and I know how to solve it with a classic if-else statement using a forEach loop without arrow functions.

Now I wonder how can I achieve this using ES6 within the forEach loop?

// Create a function that returns the product of all odd integers in an array.
const odds = [ 2, 3, 6, 7, 8 ];
const oddProduct = (arr) => {
    arr.forEach(function(element) {
        if (element % 2 === 0) {
            console.log(element);
        }
    });
};

oddProduct(odds);

I already learned how to create an arrow function for the forEach loop, but I have no clue how to add in the if-else statement.

const oddProduct = (arr) => {
    arr.forEach((element) => console.log(element));
};

Also, if someone could tell me the shortest possible way to do this using shorthand statements, I'd be happy to learn!

const oddProduct = (arr) => {
    arr.forEach((element) => {
       if (element % 2 === 0) {
         console.log(element);
       }
    });
};

Shortest possible way

const oddProduct = arr => {
      arr.forEach(element => element % 2 === 0 && console.log(element))
 };

Another way to do it would be

const oddProduct = arr => arr.forEach(e => e%2 && console.log(e))

The easiest way would be to just change the function(element) { to (element) => { :

 const odds = [ 2, 3, 6, 7, 8 ]; const oddProduct = (arr) => { arr.forEach((element) => { if (element % 2 === 0) { console.log(element); } }); }; oddProduct(odds);

If you really needed a concise body without the { , you can use && instead, but this is hard to read (I definitely wouldn't recommend it):

 const odds = [ 2, 3, 6, 7, 8 ]; const oddProduct = (arr) => { arr.forEach(element => element % 2 === 0 && console.log(element)) }; oddProduct(odds);

But I'd prefer using .filter followed by forEach instead:

 const odds = [ 2, 3, 6, 7, 8 ]; const oddProduct = (arr) => { arr .filter(element => element % 2 === 0) .forEach(element => console.log(element)); }; oddProduct(odds);

No need to do it in if-else condition, you can do it using filter function that will do magic for you please follow the below following code,

const odds = [ 2, 3, 6, 7, 8 ];

const evenValue = odds.filter((value, index, self) => {
  return self.indexOf(value) % 2 == 0;
});

console.log(evenValue)

Live Run : https://jsbin.com/qavejof/edit?js,console

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM