Remove an item from array using UnderscoreJS

后端 未结 11 2213
一向
一向 2020-12-04 06:02

Say I have this code

var arr = [{id:1,name:\'a\'},{id:2,name:\'b\'},{id:3,name:\'c\'}];

and I want to remove the item with id = 3 from the array. Is th

11条回答
  •  长情又很酷
    2020-12-04 06:15

    Use can use plain JavaScript's Array#filter method like this:

    var arr = [{id:1,name:'a'},{id:2,name:'b'},{id:3,name:'c'}];
    
    var filteredArr = arr.filter(obj => obj.id != 3);
    
    console.log(filteredArr);

    Or, use Array#reduce and Array#concat methods like this:

    var arr = [{id:1,name:'a'},{id:2,name:'b'},{id:3,name:'c'}];
    
    var reducedArr = arr.reduce((accumulator, currObj) => {
      return (currObj.id != 3) ? accumulator.concat(currObj) : accumulator;
    }, []);
    
    console.log(reducedArr);

    NOTE:

    • Both of these are pure functional approach (i.e. they don't modify the existing array).
    • No, external library is required in these approach (Vanilla JavaScript is enough).

提交回复
热议问题