Put every object in a specified bucket I have this array of objects:
const dataset = [
  {name: 'Paul', age: 10},
  {name: 'Marcus', age: 5},
  {name: 'Jennifer', age: 1},
  {name: 'Linda', age: 53},
  {name: 'Mary', age: 4},
  {name: 'Rose', age: 40},
  {name: 'Peter', age: 2},
]

and an array of ranges:
const buckets = [[0, 10], [10, 20], [20, 30], [30, 60]]

This is what I would like to get:
const result = {
  &quot;0-10&quot;: {
    res: [{name: 'Marcus', age: 5}, {name: 'Jennifer', age: 1}, {name: 'Mary', age: 4}, {name: 'Peter', age: 2}], 
    count: 4
  },
  &quot;10-20&quot;: {res: [{name: 'Paul', age: 10}], count: 1},
  &quot;20-30&quot;: {res: [], count: 0},
  &quot;30-60&quot;: {res: [{name: 'Linda', age: 53}, {name: 'Rose', age: 40}], count: 2},
}

So I would like to get an object where each key is the bucket range (as string) and each value is an object that contains two info: res should be an array of people whose age is inside that bucket (min &lt;= age &lt; max) and count is the lenght of that array.
Here is my code:
const res = buckets.reduce((acc, bucketExtent) =&gt; {
        const keyBucket = `${bucketExtent[0]}-${bucketExtent[1]}`
        const people = dataset.filter(
          (s) =&gt; s['age'] &gt;= bucketExtent[0] &amp;&amp; s['age'] &lt; bucketExtent[1]
        )
        acc[keyBucket] = {
          res: people,
          count: people.length,
        }
        return acc
      }, {})

It works but there is a smarter way? I prefer not to loop everytime the dataset array because it will be very large
From a short review;

You are definitely looping indeed over every entry 4 times
This belongs in a well named function
Other than that, it is very straight forward and understandable

I was thinking that people don't live all that long, you could easily build a lookup table for every possible age. This could speed this up quite a bit.
So something like this;


const dataset = [
  {name: 'Paul', age: 10},
  {name: 'Marcus', age: 5},
  {name: 'Jennifer', age: 1},
  {name: 'Linda', age: 53},
  {name: 'Mary', age: 4},
  {name: 'Rose', age: 40},
  {name: 'Peter', age: 2},
]

const buckets = [[0, 10], [10, 20], [20, 30], [30, 60]]

function createAgeBuckets(dataset, buckets){
  const start = 0, end = 1;
  const out = {}, ages = [];
  
  //Create age range
  for(const bucket of buckets){
    bucketRange = `${bucket[start]}-${bucket[end]}`;
    out[bucketRange] = {res: [], count: 0}; 
    for(let age = bucket[start]; age &lt; bucket[end];age++){
      ages[age] = out[bucketRange];
    }
  }

  //Create bucketses
  dataset.forEach(person =&gt; {
    ages[person.age].res.push(person);
    ages[person.age].count++;
  });

  return out;
}

console.log(createAgeBuckets(dataset, buckets));