Javascript 是否可以从array.filter方法返回每个值而不是数组?

Javascript 是否可以从array.filter方法返回每个值而不是数组?,javascript,arrays,filter,Javascript,Arrays,Filter,我结合使用.forEach和.filter数组方法来过滤一些数据。因为array.filter返回一个新数组,而我最终得到一个多维数组,所以我必须使用额外的编码步骤 有没有一个明显的解决办法我看不出来 // array with all game results var allGames = [ {id: 1, commander: 'Kerrigan', map: 'Rifts to Korhal', win: true}, {id: 1, commander: 'Kerrigan',

我结合使用.forEach和.filter数组方法来过滤一些数据。因为array.filter返回一个新数组,而我最终得到一个多维数组,所以我必须使用额外的编码步骤

有没有一个明显的解决办法我看不出来

// array with all game results
var allGames = [
  {id: 1, commander: 'Kerrigan', map: 'Rifts to Korhal', win: true},
  {id: 1, commander: 'Kerrigan', map: 'Rifts to Korhal', win: true},
  {id: 2, commander: 'Artanis', map: 'Void Thrashing', win: false},
  {id: 3, commander: 'Raynor', map: 'Dead of Night', win: true},
  {id: 4, commander: 'Alarak', map: 'Void Launch', win: true},
  {id: 5, commander: 'Dehaka', map: 'Void Launch', win: false},
  {id: 6, commander: 'Swann', map: 'Malwarfare', win: true},
  {id: 7, commander: 'Nova', map: 'Rifts to Korhal', win: true}
];

// currently selected commanders in stats window
var activeCommander = ['Kerrigan', 'Raynor', 'Nova'];

function filterGames(stats) {

  let newStats = new Array();

  activeCommander.forEach((item) => {
    // my first attempt was this, but it creates a multi-dimensional Array
    // newStats.push(stats.filter((event) => event.commander === item));

    // my workaround. using a temp array and later cycle thru
    // I don't like this extra step, is there a way to do it better?
    let temp = stats.filter((event) => event.commander === item);
    temp.forEach((tempItem)=> {
      newStats.push(tempItem);
    });
  });

  return newStats;

}

let result = filterGames(allGames);
console.log(result);
直接过滤统计数据数组:

function filterGames(stats) {
    return stats.filter(s => activeCommander.some(a => a === s.commander));
}
//所有游戏结果的数组 var allGames=[ {id:1,指挥官:'Kerrigan',地图:'Rifts to Korhal',win:true}, {id:1,指挥官:'Kerrigan',地图:'Rifts to Korhal',win:true}, {id:2,指挥官:'Artanis',地图:'Void Thashing',win:false}, {id:3,指挥官:'Raynor',地图:'DeadofNight',win:true}, {id:4,指挥官:'Alarak',地图:'Void Launch',win:true}, {id:5,指挥官:'Dehaka',地图:'Void Launch',win:false}, {id:6,指挥官:'Swann',地图:'Malwar',win:true}, {id:7,指挥官:'Nova',地图:'CRIFTS to Korhal',win:true}, ]; //统计窗口中当前选定的指挥官 var activeCommander=['Kerrigan','Raynor','Nova']; 函数filterGamesstats{ return stats.filters=>activeCommander.somea=>a==s.commander; } 让结果=filterGamesallGames; console.logresult 直接使用过滤器


您可以使用indexOf函数,它在浏览器中有很好的支持,并且运行良好

function filterGames(stats) {
    return stats.filter(s => activeCommander.indexOf(s.commander) >= 0);
}

如果commander是选择项目的主要方式,而不是数组,我会使用commander名称到每个对象的映射来快速简单地查找。我不知道。include或。some。我想我需要仔细看看数组方法。
function filterGames(stats) {
    return stats.filter(s => activeCommander.indexOf(s.commander) >= 0);
}