首页 > 解决方案 > How to get rid of an intermediate array in this case?

问题描述

I have this this function (I think the code is self-explanatory):

items: function(input) {                                                                                                                            
    let arr = [];                                                                                                                               
    for(let i=0; i<input.length; i++){                                                                                                              
         if(input[i].quantity > 0) {                                                                                                                 
             arr.push({                                                                                                                      
                 value: false,                                                                                                                                
                 name: input[i].name,                                                                                                                                                                                                                       
             });                                                                                                                                              
          }                                                                                                                                                    
    }                                                                                                                                                        
   return arr;                                                                                                                             
},  

I wonder if there is a shorter way to do it without relying on the intermediate arr?

标签: javascript

解决方案


我会使用 Array 内置方法:

items: (input) => input
        .filter(({ quantity }) => quantity > 0)
        .map(({ name }) => ({ name, value: false }))

推荐阅读