0

I have an Array ( key, startValue , EndValue);

var fruits = [[1,10, 15], [1,25, 30]];

i want to Validate before Push

console.log(push([1,5, 35]));  // false
console.log(push([2,5, 35]));  // true
console.log(push([1,30, 40])); // true
console.log(push([1,15, 25])); // true
console.log(push([1,5, 10]));  // true

console.log(fruits);

Similarly i have key 2,3,4,5, ect.

i am working with below Script.

function push(array) {
    return fruits.every(function(a) {
        return array[0] == a[0] && (array[2] <= a[1] || a[2] <= array[1]);
    }) && fruits.push(array) && true;
}
8
  • My script is work only for startValue , EndValue, not for Key. Commented Dec 6, 2016 at 11:57
  • 1
    why is that console.log(push([2,5, 35])); // true true? Commented Dec 6, 2016 at 11:59
  • Thank for respond, Not Now, it should come True. Commented Dec 6, 2016 at 12:00
  • is my approach is correct .? Commented Dec 6, 2016 at 12:01
  • oh that's what you want ? console.log(push([2,5, 35])); you want this to be true instead of false ? Commented Dec 6, 2016 at 12:01

1 Answer 1

3

You could check for the keys first.

return array[0] !== a[0] || array[2] <= a[1] || a[2] <= array[1];
//     ^^^^^^^^^^^^^^^^^^^^

function push(array) {
    return fruits.every(function(a) {
        return array[0] !== a[0] || array[2] <= a[1] || a[2] <= array[1];
    }) && fruits.push(array) && true;
}

var fruits = [[1, 10, 15], [1, 25, 30]];

console.log(push([1, 5, 35]));  // false
console.log(push([2, 5, 35]));  // true
console.log(push([1, 30, 40])); // true
console.log(push([1, 15, 25])); // true
console.log(push([1, 5, 10]));  // true
console.log(push([2, 0, 5]));   // true
console.log(fruits);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.