Dividing an array by filter function

后端 未结 12 1067
抹茶落季
抹茶落季 2020-12-01 11:24

I have a Javascript array that I would like to split into two based on whether a function called on each element returns true or false. Essentially

12条回答
  •  执念已碎
    2020-12-01 12:23

    You can use lodash.partition

    var users = [
      { 'user': 'barney',  'age': 36, 'active': false },
      { 'user': 'fred',    'age': 40, 'active': true },
      { 'user': 'pebbles', 'age': 1,  'active': false }
    ];
    
    _.partition(users, function(o) { return o.active; });
    // → objects for [['fred'], ['barney', 'pebbles']]
    
    // The `_.matches` iteratee shorthand.
    _.partition(users, { 'age': 1, 'active': false });
    // → objects for [['pebbles'], ['barney', 'fred']]
    
    // The `_.matchesProperty` iteratee shorthand.
    _.partition(users, ['active', false]);
    // → objects for [['barney', 'pebbles'], ['fred']]
    
    // The `_.property` iteratee shorthand.
    _.partition(users, 'active');
    // → objects for [['fred'], ['barney', 'pebbles']]
    

    or ramda.partition

    R.partition(R.contains('s'), ['sss', 'ttt', 'foo', 'bars']);
    // => [ [ 'sss', 'bars' ],  [ 'ttt', 'foo' ] ]
    
    R.partition(R.contains('s'), { a: 'sss', b: 'ttt', foo: 'bars' });
    // => [ { a: 'sss', foo: 'bars' }, { b: 'ttt' }  ]
    

提交回复
热议问题