Shortly, here is what I want :
it returns true when
arr=[a, b, c, d, e, f]
or
arr=[a, b, a, b, c, d, c, e, a, b]
they don't have to be in order.
and false when :
arr=[a, a, b, c, d, d, e, f]
Thank you.
You can use Array.prototype.every to test whether all elements in an array pass the test (that is a callback function returning a boolean value). In this case, make sure that the current element being checked is not the same as the previous one (index - 1), ignoring the very first element (!index).
var arr1 = ["a", "b", "c", "d", "e", "f"];
var arr2 = ["a", "a", "b", "c", "d", "d", "e", "f"];
function arrayHasConsecitiveRepetition(arrayIn) {
return arrayIn.every(function(element, index) {
return !index || element !== arrayIn[index - 1];
});
}
console.log(arrayHasConsecitiveRepetition(arr1)); // true
console.log(arrayHasConsecitiveRepetition(arr2)); // false
You can of course also do it the other way around, using Array.prototype.some to check if at least one element matches the condition, which might actually be better in terms of performance, as it stops evaluating once the condition is true*:
var arr1 = ["a", "b", "c", "d", "e", "f"];
var arr2 = ["a", "a", "b", "c", "d", "d", "e", "f"];
function arrayHasConsecitiveRepetition(arrayIn) {
return !arrayIn.some(function(element, index) {
return index && element === arrayIn[index - 1];
});
}
console.log(arrayHasConsecitiveRepetition(arr1)); // true
console.log(arrayHasConsecitiveRepetition(arr2)); // false
*Actually, it turns out that both methods return immediately once the condition is (not) met, so it's more a matter of taste or style than a matter of performance. I'd prefer to use the first approach in this case as it's clearer to me.
From the MDN pages:
If such an element is found, the
everymethod immediately returnsfalse.If such an element is found,
some()immediately returnstrue.
Array#every stop evaluating once the condition is false?If such an element is found, the every method immediately returns false.! So I guess it's not a matter of performance at all, but a matter of taste.One option:
const arr1 = ['a', 'b', 'c', 'd', 'e', 'f'];
const arr2 = ['a', 'a', 'b', 'c', 'd', 'd', 'e', 'f'];
function checkArr(arr) {
let previous;
const check = !arr.some(letter => {
if (letter === previous) {
return true;
}
previous = letter;
});
console.log(check);
}
checkArr(arr1); // true
checkArr(arr2); // false
undefined, it will return false even if the second element is not undefined. You'd probably want to check for previous && letter === previous
a => a.every((n, i) => i === 0 || n !== a[i - 1])