var array = [
{ T: 2, G: 2, K: 2}, //<--- return this cause T+G+K = 6
{ T: 2, G: 2, K: 3},
{ T: 1, G: 3, K: 2} //<--- return this cause T+G+K = 6
];
我想从数组返回相同数量的字段对象。怎么做?
我当时想:
var array = [
{ T: 2, G: 2, K: 2 }, //<--- return this cause T+G+K = 6
{ T: 2, G: 2, K: 3 },
{ T: 1, G: 3, K: 2 } //<--- return this cause T+G+K = 6
];
//getting uniq array
var uniqArray = _.uniq(array, function(value) {
return value.T + value.G + value.K;
}
//uniqArray = [
// { T: 2, G: 2, K: 2 },
// { T: 2, G: 2, K: 3 }
//];
//getting the difference between uniq and normal array
var differenceArray = _.difference(array, uniqArray);
//differenceArray = [
// { T: 1, G: 3, K: 2 }
//];
//and finally try to get the same objects in array like:
var theSame = [];
_.each(array, function(value) {
if((value.T + value.G + value.K) === _.each(differenceArray, function(num) {
return num.T + num.G + num.K; }) {
theSame.push(value);
}
);
但我真的不知道下划线,所以我认为我试图通过过多使用并使其变得太难来做某事。我怎样才能轻松获得这些物品?
谢谢
答案 0 :(得分:0)
如果我理解你,这应该最终有用。
var array = [
{ T: 2, G: 2, K: 2 },
{ T: 2, G: 2, K: 3 },
{ T: 1, G: 3, K: 2 }
];
var uniqArray = _.uniq(array, function(value) {
return value.T + value.G + value.K;
});
var differenceArray = _.difference(array, uniqArray);
var sums = _.map(differenceArray, function(item) {
return item.T + item.G + item.K;
});
var result = _.filter(array, function(item) {
var sum = item.T + item.G + item.K;
return _.contains(sums, sum);
});
更干净的版本:
var arraySum = function(item) {
return item.T + item.G + item.K;
};
var notUniqueSums = _.chain(array)
.difference(_.uniq(array, arraySum))
.map(arraySum)
.value();
var result = _.filter(array, function(item) {
return _.contains(notUniqueSums, arraySum(item));
});