Remove multiple elements from array in Javascript/jQuery

后端 未结 22 2364
梦毁少年i
梦毁少年i 2021-01-29 19:42

I have two arrays. The first array contains some values while the second array contains indices of the values which should be removed from the first array. For example:

<
22条回答
  •  悲&欢浪女
    2021-01-29 20:32

    This works well for me and work when deleting from an array of objects too:

    var array = [ 
        { id: 1, name: 'bob', faveColor: 'blue' }, 
        { id: 2, name: 'jane', faveColor: 'red' }, 
        { id: 3, name: 'sam', faveColor: 'blue' }
    ];
    
    // remove people that like blue
    
    array.filter(x => x.faveColor === 'blue').forEach(x => array.splice(array.indexOf(x), 1));
    

    There might be a shorter more effecient way to write this but this does work.

提交回复
热议问题