Javascript filter array by data from another

后端 未结 7 1596
滥情空心
滥情空心 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:24

    You can use a for loop on the object array and check hasOwnProperty in another for loop for each ids in [1,3,5] (break out of the loop once an id found). (And break out of the bigger for-loop once all ids are found) If your array object is ordered (e.g. elements sorted from smallest id to biggest id) and so are your list, this solution should be quite efficient.

    var c = 0;
    for(var i =0; i< objects.length; i++){
      for(var v =0; v< list.length; v++)
         if(objects[i].hasOwnProperty(list[v])){ 
           delete objects[i]; c++; break; 
         }
      if(c===list.length) break;
    }
    

    or use array.splice( i, 1 ); if you don't want an empty slot.

提交回复
热议问题