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

时间:2017-10-27 14:43:10

标签: 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', 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);

3 个答案:

答案 0 :(得分:3)

直接过滤stats数组:

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

// 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) {
	return stats.filter(s => activeCommander.some(a => a === s.commander));
}

let result = filterGames(allGames);
console.log(result);

答案 1 :(得分:3)

直接使用过滤器includes

function filterGames(stats) {
  return stats.filter(game => activeCommander.includes(game.commander))
}

答案 2 :(得分:2)

你可以使用indexOf函数,它在浏览器中有很好的支持,效果很好

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