Javascript filter array by data from another

后端 未结 7 1568
滥情空心
滥情空心 2020-11-27 22:50

I have an array object:

[
    { id:1, name: \'Pedro\'},
    { id:2, name: \'Miko\'},
    { id:3, name: \'Bear\'},
    { id:4, name: \'Teddy\'},
    { id:5, n         


        
相关标签:
7条回答
  • 2020-11-27 23:31

    Using filter and indexOf will do the trick:

    var filteredArray = dataArray.filter(function(obj) {
      return idsArray.indexOf(obj.id) > -1;
    });
    

    However, indexOf has linear performance, and it will be called lots of times.

    In ES6 you can use a set instead, whose has call has sublinear performance (on average):

    var idsSet = new Set(idsArray),
        filteredArray = dataArray.filter(obj => idsSet.has(obj.id));
    

    Assuming the toString method of your ids is injective, you can achieve something similar in ES5:

    var idsHash = Object.create(null);
    idsArray.forEach(function(id) {
      idsHash[id] = true;
    });
    var filteredArray = dataArray.filter(function(obj) {
      return idsHash[obj.id];
    });
    
    0 讨论(0)
提交回复
热议问题