我有一个数组[{lowlimit: 0, highlimit 100}, {lowlimit: 201, highlimit: 300}]
应该接受一个新元素{lowlimit: 301, highlimit: 400}
或{lowlimit: 101, highlimit: 150}
但不应接受像{lowlimit: 50, highlimit: 80}
或{lowlimit: 50, highlimit: 250}
这样的元素,因为它属于现有的元素之一或与现有范围重叠
有任何建议如何在javascript或打字稿中检查?
你需要遵循一些步骤:
请在循环内使用下面的函数来迭代数组。
function _isBetweenRange(a, b){
var aLowLimit = a.lowlimit;
var aHighLimit = a.highlimit;
var bLowLimit = b.lowlimit;
var bHighLimit = b.highlimit;
if(bLowLimit >= aLowLimit && bHighLimit <= aHighLimit){
return true;
}else{
return false;
}
}
试试这个。您可以添加任何值。然后你需要获得独特的价值而不是添加。像这样下面的方式。
var a = [{lowlimit: 0, highlimit : 100}, {lowlimit: 201, highlimit:300},
{lowlimit: 50, highlimit: 300}, {lowlimit: 50, highlimit: 300}];
var elementId = [];
var newArr = a.filter(function(el, index){
if (elementId.indexOf(el.lowlimit) === -1) {
elementId.push(el.lowlimit);
return true;
} else {
return false;
}
});
console.log(newArr);
在下面的片段中:shouldpush()
测试object
是否应该是pushed
到array
(根据你的规则)。
shouldpush()
returns
resulting
array
(按顺序),形式为[bool, newarray]
。
你可以像这样收集result
:const [push, newarray] = shouldpush(array, object)
// Array.
const array = [{lowlimit: 0, highlimit: 100}, {lowlimit: 201, highlimit: 300}]
// Should Push.
const shouldpush = (array, object) => {
const length = array.length
for (let i = 0; i <= (length-1); i ++) {
// Comps.
const pre = array[i] || false
const post = array[i+1] || false
// Cases:
// Length(1) AND Fit Above (Extreme Edge Case).
if ((length == 1) && (pre.highlimit < object.lowlimit)) return [true, [...array, object]]
// First Fit (Below).
const atfirst = (i == 0) // At First Index.
const firstfit = (atfirst && (pre.lowlimit > object.highlimit)) // First Fit.
if (firstfit) return [true, [object, ...array]] // True.
// Normal Fit.
const lowfit = (object.lowlimit > pre.highlimit) // Standard Low.
const highfit = (object.highlimit < post.lowlimit) // Standard High.
if (lowfit && highfit) return [true, [...array.slice(0, i+1), object, ...array.slice(i+1)]]
// Last Fit (Above).
const atlast = (i == (length - 2)) // At Last Index.
const lastfit = (atlast && (post.highlimit < object.lowlimit)) // Last Fit.
if (lastfit) return [true, [...array, object]] // True.
// No Fit.
if (!lowfit && !highfit) return [false, [...array]] // !Fit (Early Exit).
}
return [false, [...array]] // !Fit.
}
// Test Objects.
const w = {lowlimit: 301, highlimit: 400} // W.
console.log(shouldpush(array, w)) // True.
const x = {lowlimit: 101, highlimit: 150} // X.
console.log(shouldpush(array, x)) // True.
const y = {lowlimit: 50, highlimit: 80} // Y.
console.log(shouldpush(array, y)) // False.
const z = {lowlimit: 50, highlimit: 250} // Z.
console.log(shouldpush(array, z)) // False.
// Example Retrieval.
const [push, newarray] = shouldpush(array, x)
console.log(push, newarray) // Push. New Array.