拆分和组数组javascript / jquery

时间:2014-01-19 20:18:47

标签: javascript jquery

我有

range = [a,3,b,2,c,1,d,2,e,3,f,3]

并且需要将a,b,c,d,e,f分组为3个相同大小的组,具体取决于它们的值。

正确的结果将是:

group1 = [a]
group2 = [b,c]
group3 = [d,e,f]

更新:模式 - >只有group3可以大于总组的1/3。我到目前为止:

var range = [3,2,1,2,3,3]
var total = 14;
var group_size = total / 3;
var values = [0];
var groupnr = 0;
range = range.reverse();

while( range.length ) {
var curvalue = range.pop();

if( values[groupnr] + curvalue > group_size && groupnr < 2 ) {
     groupnr++;
     values[groupnr] = 0;
}
values[groupnr] += curvalue;
}
log(values);

2 个答案:

答案 0 :(得分:1)

这样的东西
var range = ['a',3,'b',2,'c',1,'d',2,'e',3,'f',3];
var obj = {};

range.map(function(el, i) {
    if (i%2) {
        var k = 'group'+el;
        obj[k] = obj[k] || [];
        obj[k].push(range[i-1]);
    }
});

给你

{
    "group1" : ["c"]
    "group2" : ["b","d"],
    "group3" : ["a","e","f"],
} 

FIDDLE

那是唯一有意义的事情吗?

答案 1 :(得分:0)

至少有一种可能性:

var equalSplit = (function() {
    var sum = function(list) {return list.reduce(function(a, b) {
        return a + b;
    }, 0);};
    var evens = function(list) {
        return list.filter(function(item, index) {return !(index % 2);})
    };
    var odds = function(list) {
        return list.filter(function(item, index) {return !!(index % 2);})
    };
    var split = function(values, count) {
        var mean = sum(values) / values.length;
        var groups = [], index = 0, total, groupStart;
        for (var i = 0; i < count - 1; i++) {
            total = 0; groupStart = index;
            while (index < values.length && total < mean) {
                total += values[index++];
            }
            groups.push(values.slice(groupStart, index));
        }
        groups.push(values.slice(index));
        return groups;
    };
    var reconstituteRanges = function(ranges, splits) {
        var groups = {}, ctr = 0, diff;
        for (var i = 0; i < splits.length; i++) {
            diff = splits[i].length
            groups["group" + (i + 1)] = 
                    (evens(ranges.slice(ctr, ctr+=(2 * diff))));
        }
        return groups;
    };
    return function(ranges, count) {
        var values = odds(ranges);
        var splits = split(values, count);
        return reconstituteRanges(ranges, splits);
    }
}());

var ranges = ['a',3,'b',2,'c',1,'d',2,'e',3,'f',3];
console.log(equalSplit(ranges, 3));
//=> {"group1":["a"],"group2":["b","c"],"group3":["d","e","f"]}

您可以在 JSFiddle 上看到它。

这个问题比 an earlier version 简单得多,虽然代码不会那么短。

但你真的想让最后一组承担这样的重量吗?你最初发布的希望它们更接近平等。在这种情况下,你的加权总数是[3,3,8],相当高的方差为16.67,其中[['a'],['b','c','d'],['e', 'f']]会在[3,5,6]更好地平衡,方差仅为4.67。这真的是你的要求,还是只是一种编写更简单代码的方法? (虽然这段代码并不比我之前的答案简短得多,但它简单得多。)