Reputation:
Write a function that finds whether an array has 3 increasing consecutive numbers in it or not. If there is, return 1. Otherwise, return 0.
function tripleThreat(arr) {
if (arr.find((i) => arr[i] + arr[i + 1] + arr[i + 2])) {
return 1
}
return 0
}
tripleThreat([3,1,2,3]);
Sample output
[...34,35,36...]
would return 1
How would I write this using the array.find()
method?
Some tests are passing, some aren't.
Right now, if I input [3, 1, 2, 3]
, the result is 0
and not 1
.
Upvotes: 0
Views: 754
Reputation: 20269
Use the 2nd parameter of Array.find
to check the next two numbers for being greater than the current and the one after the current respectively. Don't forget to check if the array is long enough to have two more indices after the current one.
Array.find
returns undefined
if it can't find any matching elements, so if it returns undefined
, then you know no such match exists and should return 0. Otherwise, return 1.
function tripleThreat(arr) {
if (arr.find((v,i) =>
arr.length > i+2
&& v < arr[i+1]
&& arr[i+1] < arr[i+2]) === undefined) {
return 0;
}
return 1;
}
console.log(tripleThreat([3,1,2,3]));
console.log(tripleThreat([3,1,3,3]));
console.log(tripleThreat([0,1,2,2]));
console.log(tripleThreat([1,2,2.1,3]));
If you need to check if the values are consecutive whole numbers, check for equality to the current value plus one or two:
function tripleThreat(arr) {
if (arr.find((v,i) =>
arr.length > i+2
&& v + 1 === arr[i+1]
&& v + 2 === arr[i+2]) === undefined) {
return 0;
}
return 1;
}
console.log(tripleThreat([3,1,2,3]));
console.log(tripleThreat([3,1,3,3]));
console.log(tripleThreat([0,1,2,4]));
console.log(tripleThreat([1,2,2.1,3]));
Upvotes: 1