I have an array: A = [ 2, 2, 0, 0, -1, 1, -1, -1, -1 ]
I want to be able to return true in instances where 2 or more consecutive numbers are the same. So in this array, the output array should have 5 trues with [2,2], [0,0], [-1,-1,-1], [-1,-1] and [-1,-1].
So far I have used slice and map on the array through 2 consecutive numbers and have gotten 4 trues.
const solution = (A) => {
let compare = A.slice(1).map((n,i) => {
return (n === A[i])
})
console.log(compare) // => [ true, false, true, false, false, false, true, true ]
}
const A = [ 2, 2, 0, 0, -1, 1, -1, -1, -1 ];
solution(A);
But getting that fifth true on the [-1,-1,-1] is eluding me.
Currently the compare output I have is only going through 2 consecutive numbers which is why it's given me 4 trues. My question is basically how to go about checking for the 3 or more consecutive numbers.
My final would be something like
compare.filter(word => word === true).length
to get 5.
Perhaps what would actually be useful is the groups:
const findGroups = (arr) => arr.reduce((result, value, index) => {
let windowLength = 2;
while (arr[index + windowLength - 1] === value) {
result.push(arr.slice(index, index + windowLength));
windowLength++;
}
return result;
}, []);
console.log(findGroups([2, 2, 0, 0, -1, 1, -1, -1, -1])); // [[2, 2], [0, 0], [-1, -1], [-1, -1, -1], [-1, -1]]
console.log(findGroups([4, 4, 4, 4])); // [[4, 4], [4, 4, 4], [4, 4, 4, 4], [4, 4], [4, 4, 4], [4, 4]]
That gives you an array of the groups of consecutive values. If you just want 5, it's the .length, or you can calculate it directly rather than building unnecessary arrays:
const findGroupCount = (arr) => arr.reduce((result, value, index) => {
let windowLength = 2;
while (arr[index + windowLength - 1] === value) {
result++;
windowLength++
}
return result;
}, 0);
console.log(findGroupCount([2, 2, 0, 0, -1, 1, -1, -1, -1])); // 5
console.log(findGroupCount([4, 4, 4, 4])); // 6
Checking for duplicate strings in JavaScript array
The above question/answer is a great place to start. But to explicitly what you want:
const A = [ 2, 2, 0, 0, -1, 1, -1, -1, -1 ]
let findDuplicates = arr => arr.filter((item, index) => arr.indexOf(item) != index)
const solutionArray = findDuplicates(A).map((e) => true);
console.log(solutionArray); // [true, true, true, true, true]
To do this consecutively your code works as expected:
[2,2] True [2,0] False [0,0] True [0,-1] False [-1,1] False [1,-1] False [-1,-1] True [-1,-1] True
That's the comparisons in order comparing 2 consecutive numbers. The 5th true that you're hoping for is comparing 3 consecutive numbers.
Are you asking for a solution that would also compare (n) number of consecutive numbers?