Skip to content Skip to sidebar Skip to footer

Avoid No-sequences Inside Map Function

I have a array which I want to loop through so I use the map prototype. Inside the callbackfn of each element I want to run several expressions. const test = [{ name: 'foo', value:

Solution 1:

How am I meant to put multiple expressions inside the map function?

Use curly braces:

test.map(name => {
   console.log(name.name)
   console.log(name.value)
   found = true
});

Though map doesn't look the right choice for this as pointed out others - looks like you should use filter, but the same rules apply for multiple statements.

Normal brackets are a shorthand for 'implied return', where you can omit the {} and the return keyword if your function only contains one expression. In fact, you can usually omit the brackets too!

So these are equivalent:

test.filter(name => {
    let found = falseif(name==='sarah'){
       found = true
    }
    return found 
}

test.filter(name => name === 'sarah')

Solution 2:

You have a syntax error in your code, since the correct syntax for an arrow function with multiple lines of code is:

(params) => {
  // Your code here with semicolon at line end
}

Note the use of curly braces instead of parentheses and the semicolon instead of comma at line end.

Also, since you are seeking for some value inside and don't care about it position, you can use Array.some() instead. It will be more efficient since it stops on first result:

let found = test.some((name) => {
  if (your condition here) {
    returntrue;
  } else {
    returnfalse;
  }
});

Post a Comment for "Avoid No-sequences Inside Map Function"