基于值绑定填充数组

时间:2017-02-01 20:12:12

标签: javascript node.js

我需要根据一个人的“年龄”创建一个数据数组。这个条带不是线性的,而是分组类似

1,2,3,4,5,6,7,8,9,10,11-15,16-20,21-30,31-50,51 +

所以对于任何一组数据,我需要通过这个并将该人置于适当的年龄“桶”

在循环结束时,我想看看每个乐队中有多少人。

现在,我已经通过使用非常粗糙的技术(也就是如果这......然后..如果......);)来做到这一点,但是想知道我是否可以学习新技术以及是否有任何库或功能可以取一个范围并相应填充桶

3 个答案:

答案 0 :(得分:3)

这就是我要做的事情:

let buckets = '1,2,3,4,5,6,7,8,9,10,11-15,16-20,21-30,31-50,51+'.split(','),
    bucketByAge = {}; // our bucket-age connector where we search later on

// prepare the index
buckets.forEach(function(bucket, index) {
  // get the range (+ will be replaced with 1000; for the age it is infinity)
  // and transform them to numbers
  let range = bucket.replace('+', '-1000').split('-').map(Number);

  // if it was not a range, simulate one
  range[1] = range[1] || range[0];

  // go through the range and fill our connector
  while (range[0] <= range[1]--) {
    bucketByAge[range[1]] = index;
  }
});

// search
function getBucket(age) {
  return { age: age, bucketRange: buckets[bucketByAge[age]], bucketIndex: bucketByAge[age] };
}

console.log(getBucket(1));
console.log(getBucket(12));
console.log(getBucket(61));

这里有什么好处:你建立一次索引,然后只取结果。非常高效。

答案 1 :(得分:0)

非常粗略的o(n ^ 2)实现

const buckets = [
  {
    lowerLim: 1,
    upperLim: 1,
    persons: 0
  },
  {
    lowerLim: 2,
    upperLim: 2,
    persons: 0
  },
  {
    lowerLim: 3,
    upperLim: 5,
    persons: 0
  },
  {
    lowerLim: 6,
    upperLim: 10,
    persons: 0
  },
  {
    lowerLim: 11,
    persons: 0
  }
];


const persons = [{name: 'john', age: 1},{name: 'john', age: 2}, {name: 'john', age: 6}, {name: 'john', age: 20}, {name: 'john', age: 40}, {name: 'john', age: 7}, {name: 'john', age: 1}];

persons.forEach(person => {
  buckets.forEach(bucket => {
    const age = person.age;
    const bucketLowerLimit = bucket.lowerLim;
    const bucketUpperLimit = bucket.upperLim || Number.MAX_SAFE_INTEGER;

    if(age >= bucketLowerLimit && age <= bucketUpperLimit) {
      bucket.persons++;
    }
  })
});


buckets.forEach(bucket => {
  console.log(bucket.persons);
});

答案 2 :(得分:0)

您可以为中间的所有值和单独的最后一个值使用引用。

var slots = '1,2,3,4,5,6,7,8,9,10,11-15,16-20,21-30,31-50,51+'.split(','),
    last = slots.pop(),
    reference = Object.create(null),
    histogram = Object.create(null),
    i, value;

slots.forEach(function (a) {
    var temp = a.split('-'),
        left = temp[0],
        right = temp[1] || temp[0];

    histogram[a] = 0;
    reference[right] = a;
    while (left < right) {
        reference[left] = a;
        left++;
    }
});

histogram[last] = 0;

for (i = 0; i < 1000000; i++) {
    value = Math.floor(Math.random() * 100);
    histogram[reference[value] || last]++;
}

console.log(histogram);
console.log(reference);
.as-console-wrapper { max-height: 100% !important; top: 0; }