function isArrayWithIdenticalElements(array) {
return array.length > 1 && !!array.reduce(function(a, b){ return (a === b) ? a : NaN; });
}
function noRepetition(numberOfRepetition, array) {
var sliceLength = numberOfRepetition - 1;
var pointer = sliceLength;
var element = array[pointer];
while (element) {
if (isArrayWithIdenticalElements(array.slice(pointer - sliceLength, pointer + 1))) {
array.splice(pointer - sliceLength, numberOfRepetition);
pointer = pointer - sliceLength;
element = array[pointer];
} else {
pointer = pointer + 1;
element = array[pointer];
}
}
return array;
}
var noDoubles = noRepetition.bind(null, 2);
var noTriplets = noRepetition.bind(null, 3);
var noQuadruples = noRepetition.bind(null, 4);
console.log('noTriplets([1,1,1,3,3,5] ==> ', noTriplets([1,1,1,3,3,5])); // = [3,3,5]
console.log('noTriplets([1,1,1,1,3,5] ==> ', noTriplets([1,1,1,1,3,5])); // = [1,3,5]
console.log('noTriplets([1,1,1,1,1,5] ==> ', noTriplets([1,1,1,1,1,5])); // = [1,1,5]
console.log('noTriplets([1,1,1,5,5,5] ==> ', noTriplets([1,1,1,5,5,5])); // = []
console.log('noTriplets([1,1,1,1,1,1] ==> ', noTriplets([1,1,1,1,1,1])); // = []
console.log('noQuadruples([1,1,1,3,3,5] ==> ', noQuadruples([1,1,1,3,3,5])); // = [1,1,1,3,3,5]
console.log('noQuadruples([1,1,1,1,3,5] ==> ', noQuadruples([1,1,1,1,3,5])); // = [3,5]
console.log('noDoubles([1,1,1,5,5,5] ==> ', noDoubles([1,1,1,5,5,5])); // = [1,5]
這取決於你考慮容易...你搞什麼名堂到目前爲止做了什麼? – Teemu
嘿喬 - 你能確認你要找的條件嗎?在示例3中,您在數組中返回了兩個'1',但在示例4和5中,返回none。條件是每次有一個數字有三個時,刪除這三個,但如果有四個,則您想要返回1.如果有6個,您希望因爲刪除3和3而不返回任何一個。是這樣嗎? –
@ChristopherMesser你是對的。我想刪除數組中的任何三元組。 –