简体   繁体   中英

if/else statement in map function?

I am here want to use map function in javascript to loop a type data array,but i get error for these syntax below :

function porti(scores) {
const test = scores.map(pass, fail) => {
    if (scores < 75){
      test.fail
    } else {
      test.pass
    }
    return {pass, fail}
  }

}

output must be, if scores < 75 : fail, else : pass

console.log(porti([80, 45, 90, 65, 74, 100, 85, 30]));
// { pass: [ 80, 90, 100, 85 ], fail: [ 45, 65, 74, 30 ] }

console.log(porti([]));
// { pass: [], fail: [] }

I think reduce would be better for this situation. This will allow us to reduce the array to an object of two item arrays.

 let items = [80, 45, 90, 65, 74, 100, 85, 30] let result = items.reduce((obj, item) => { item < 75 ? obj.fail.push(item) : obj.pass.push(item) return obj }, {pass:[], fail:[]}) console.log(result) 

If you wanted to use filter you could...

 let items = [80, 45, 90, 65, 74, 100, 85, 30] let result = { pass: items.filter(i => i >= 75), fail: items.filter(i => i < 75) } console.log(result) 

And here is how we can do it with forEach...

 let items = [80, 45, 90, 65, 74, 100, 85, 30] let result = {pass:[], fail:[]} items.forEach(itm => itm < 75 ? result.fail.push(itm) : result.pass.push(itm)) console.log(result) 

You could integrate the check as ternary for getting the key for pushing.

 function porti(scores) { var result = { pass: [], fail: [] }, score; for (score of scores) { result[score < 75 ? 'fail': 'pass'].push(score); } return result } console.log(porti([80, 45, 90, 65, 74, 100, 85, 30])); console.log(porti([])); 
 .as-console-wrapper { max-height: 100% !important; top: 0; } 

As mentioned above .map() should best be saved for when you are looking to return an array by manipulating a previous array. If you don't wish to use a vanilla for loop. You could try this

const testScores = [...someArray of numbers]
function porti(tesScores) {    
const result = {
   pass: [],
   fail: []
}
    for (let score of testScores) {
        if (score < 75) {
           result.fail.push(score)
         } else {
           result.pass.push(score)
         }
  return result      
}}

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