DEV Community

artydev
artydev

Posted on • Edited on

Partition arrays in Javascript using reduce.

Suppose you have to partition an array of number given some predicates, how would you procede ?

I want for example, partition an array given the following predicates :

 [
    (x) => x % 3 == 0, 
    (x) => x % 4 == 0
 ]
Enter fullscreen mode Exit fullscreen mode

Below the partition function.

The nice thing is that we do all the treatment in one pass, without relying on the filter method.

Thanks to the reduce method.

function  partition(data, predicates = []) {
  const lp = predicates.length;
  return data.reduce((buckets, element) => {
    for (j = 0; j < lp; j++) {
      if (predicates[j](element)) {
        buckets[j].push(element);
      }
    }
    return buckets.map(t => t.sort((x,y) => x - y));
  }, 
  // Here we create as many arrays (buckets) as predicates
  // This array of 'buckets' constitute the accumulator
  // of the reducer.
  [...Array(lp)].map(() => []));
}

const a = [16,8,1,27,3,2,4,6,9,11]

console.log(
  partition(a, [
    (x) => x % 3 == 0, 
    (x) => x % 4 == 0
  ])
)


Enter fullscreen mode Exit fullscreen mode

You can play with it here Partition

Result :


[ [ 3, 6, 9, 27 ], [ 4, 8, 16 ] ]

Enter fullscreen mode Exit fullscreen mode

Don't hesitate to comment, correct or enhance.

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay