[英]Array.prototype.sort() for object pairs
我在一个对象数组中得到一个函数的结果:
let options = [
{
"aCol": 0,
"aRow": 10,
"bCol": 12,
"bRow": 4,
"cCol": 5,
"cRow": 1,
},
{
"aCol": 4,
"aRow": 10,
"bCol": 3,
"bRow": 4,
"cCol": 1,
"cRow": 1,
},
{
"aCol": 4,
"aRow": 10,
"bCol": 3,
"bRow": 0,
"cCol": 0,
"cRow": 1,
}
];
我想检查值对,即:
aCol
aRow
并按三对中零的数量按升序对它们进行排序。 结果应该是:
let options = [
{
"aCol": 4,
"aRow": 10,
"bCol": 3,
"bRow": 0, // b contains a zero
"cCol": 0, // c contains a zero
"cRow": 1,
},
{
"aCol": 0, // a contains a zero
"aRow": 0,
"bCol": 12,
"bRow": 4,
"cCol": 5,
"cRow": 1,
},
{
"aCol": 4, // no zeroes in this object in any of the pairs
"aRow": 10,
"bCol": 3,
"bRow": 4,
"cCol": 1,
"cRow": 1,
},
];
我一直在利用零和这样的快捷方式搞砸:
options.sort((x,y) =>
(x.aCol * x.aRow < y.aCol * y.aRow) ||
(x.bCol * x.bRow < y.bCol * y.bRow) ||
(x.cCol * x.cRow < y.cCol * y.cRow)
)
console.log(...options);
let options = [
{
"aCol": 1,
"aRow": 10,
"bCol": 12,
"bRow": 4,
"cCol": 0,
"cRow": 1,
},
{
"aCol": 4,
"aRow": 10,
"bCol": 3,
"bRow": 4,
"cCol": 1,
"cRow": 1,
},
{
"aCol": 4,
"aRow": 10,
"bCol": 3,
"bRow": 0,
"cCol": 0,
"cRow": 1,
}
];
const sorted = options.sort((x, y) => {
const xZeros = +!(x.aCol * x.aRow) + +!(x.bCol * x.bRow) + +!(x.cCol * x.cRow);
const yZeros = +!(y.aCol * y.aRow) + +!(y.bCol * y.bRow) + +!(y.cCol * y.cRow);
return yZeros - xZeros
})
console.log(sorted)
对我有用测试
+!(x.aCol * x.aRow)
因此,如果乘法为零,则将其反转为“真”,然后“+”将其转换为 1;
如果乘法大于 0,则将其反转为 false,然后为 0
function compareColAndRowZeroCounts(a, b) { const productZeroCountA = [ (a.aCol * a.aRow), (a.bCol * a.bRow), (a.cCol * a.cRow) ].filter(num => !num).length; const productZeroCountB = [ (b.aCol * b.aRow), (b.bCol * b.bRow), (b.cCol * b.cRow) ].filter(num => !num).length; const totalZeroCountA = Object.values(a).filter(num => !num).length; const totalZeroCountB = Object.values(b).filter(num => !num).length; // ascending order return ((productZeroCountA > productZeroCountB) && -1) || ((productZeroCountA < productZeroCountB) && 1) || ((totalZeroCountA > totalZeroCountB) && -1) || ((totalZeroCountA < totalZeroCountB) && 1) || 0; } const options = [{ "aCol": 0, "aRow": 0, "bCol": 12, "bRow": 4, "cCol": 5, "cRow": 1, }, { "aCol": 4, "aRow": 10, "bCol": 3, "bRow": 4, "cCol": 1, "cRow": 1, }, { "aCol": 4, "aRow": 10, "bCol": 3, "bRow": 0, "cCol": 0, "cRow": 1, }]; console.log( 'options.sort(compareColAndRowZeroCounts)', options.sort(compareColAndRowZeroCounts) );
.as-console-wrapper { min-height: 100%!important; top: 0; }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.