I have an array :
main = [{
data: x,
numberField: 1;
}, { data: y,
numberField: 2;
}, { data: x,
numberField: 3;
},
{ data:z
numberField: 4;
},
{ data: q
numberField: 5;
}]
fixedElements = [ 3, 5]
I need to have :
fixedElements .includes(a.numberField) - fixedElements .includes(b.numberField)
Because I need to check whether two coming values are in the array a and not sort them, but sort the rest. when I try to do this typescript throws an error
left/right hand-side of the argument needs to be of type any or number.
My initial sort function as :
sort(a,b) {
if(a.numberField > b.numberField)
return -1
if(a.numberField < b.numberField)
return 1;
}
So I wanted to check whether the coming a or b are in the fixedElements array, and leave them last. Is there any other way to do this?
You can cast the booleans to numbers by using the +
sign (typescript playground demo):
+fixedElements.includes(a.numberField) - +fixedElements.includes(b.numberField)`
And this is the sort logic (typescript playgroud - check console):
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With