我有一个数组:
main = [{
data: x,
numberField: 1;
}, { data: y,
numberField: 2;
}, { data: x,
numberField: 3;
},
{ data:z
numberField: 4;
},
{ data: q
numberField: 5;
}]
fixedElements = [ 3, 5]
我需要:
fixedElements .includes(a.numberField) - fixedElements .includes(b.numberField)
因为我需要检查两个即将到来的值是否在数组a中而不是对它们进行排序,而是对其余值进行排序。 当我尝试这样做时,打字错误
left/right hand-side of the argument needs to be of type any or number.
我的初始排序功能为:
sort(a,b) {
if(a.numberField > b.numberField)
return -1
if(a.numberField < b.numberField)
return 1;
}
所以我想检查即将到来的a或b是否在fixedElements数组中,并将它们保留到最后。还有其他办法吗?
答案 0 :(得分:0)
您可以使用+
符号(typescript playground demo)将布尔值转换为数字:
+fixedElements.includes(a.numberField) - +fixedElements.includes(b.numberField)`
这是排序逻辑(typescript playgroud - 检查控制台):
const main = [{"data":"x","numberField":1},{"data":"y","numberField":2},{"data":"x","numberField":3},{"data":"z","numberField":4},{"data":"q","numberField":5}]
// I'm using a Set instead of an array, because Set.has is faster than Array.includes
const fixedElements = new Set([3, 5])
main.sort((a, b) => {
const aF = fixedElements.has(a.numberField)
const bF = fixedElements.has(b.numberField)
if(!aF && !bF) return b.numberField - a.numberField
return +aF - +bF
})
console.log(main)
&#13;
答案 1 :(得分:0)
您可以使用自定义排序功能并检查numberField
数组中是否存在fixedElements
值并保持未排序,否则根据numberField
值对其进行排序。
let main = [{ data: 'x', numberField: 1}, { data: 'y', numberField: 2}, { data: 'x', numberField: 3}, { data:'z', numberField: 4}, { data: 'q', numberField: 5}],
fixedElements = [3, 5];
main.sort((a,b) => {
if([a,b].some(({numberField}) => fixedElements.includes(numberField)))
return +fixedElements.includes(a.numberField) - +fixedElements.includes(b.numberField);
else
return +b.numberField - +a.numberField
});
console.log(main);
&#13;
答案 2 :(得分:0)
您可以使用includes()
方法中的sort
方法进行检查。
var array = [{
data: 'x',
numberField: 1
}, {
data: 'y',
numberField: 2
}, {
data: 'x',
numberField: 3
}, {
data: 'z',
numberField: 4
}, {
data: 'q',
numberField: 5
}],
fixedElements = [3, 5];
array.sort((a, b) => {
a = +a.numberField;
b = +b.numberField;
return (fixedElements.includes(a) - fixedElements.includes(b) || b - a);
});
console.log(array)