3 ways to partition an array based on a condition using javascript ES6

In this tutorial we will learn how to partition an array based on a condition using javascript. we will see multiple ways to do this and also explore some solutions using lodash or other 3rd party libs.

Article Contents

Partition an array javascript using Array.reduce

const partitionArr = (arr, condn) => arr.reduce((acc, i) => (acc[condn(i) ? 0 : 1].push(i), acc), [[], []]);

const intArr = [2,4,8,9,11,10,12];

partitionArr(intArr, (n) => n > 8); // output: [[9,11,10,12],[2,4,8]]

Partition an array javascript using Array.filter

Javascript Array.filter function can be used to achieve this partining as following

const users = [
  { 'user': 'Vishal',  'age': 26, 'active': 1},
  { 'user': 'Sangu',    'age': 30, 'active': 0},
  { 'user': 'Aryan', 'age': 19,  'active': 1}
];

const partitionArr = (arr, condn) => {
    const trues = arr.filter(el => condn(el));
    const falses = arr.filter(el => !condn(el));
    return [trues, falses];
};

const [active, inactive] = partitionArr(users, (el) => el.active);
// → output ['Vishal', 'Aryan'] and ['Sangu']


Partition an array javascript using Lodash _.partition

Lodash provides an util function to do _.partition. if you want to use lodash then you can use this function as below.
and it can be used on array of objects as well.

const intArr = [2,4,8,9,11,10,12];

_.partition(intArr, (n) => n > 8); // output: [[9,11,10,12],[2,4,8]]

const users = [
  { 'user': 'Vishal',  'age': 26, 'active': 1},
  { 'user': 'Sangu',    'age': 30, 'active': 0},
  { 'user': 'Aryan', 'age': 19,  'active': 1}
];

_.partition(users, function(o) { return o.active; });
// → output [['Vishal', 'Aryan'], ['Sangu']]

// The `_.matches` iteratee shorthand.
_.partition(users, { 'age': 30, 'active': 0});
// → output [['Sangu'], ['Vishal', 'Aryan']]

// The `_.matchesProperty` iteratee shorthand.
_.partition(users, ['active', 0]);
// → output [['Vishal', 'Aryan'], ['Sangu']]

// The `_.property` iteratee shorthand.
_.partition(users, 'active');
// → output [['Vishal','Aryan'], ['Sangu']]

See also  Access getter from another vuex module

Leave a Comment