我正在尝试用JavaScript做一些有趣的事情,但我做不到.这是我的意见:
var Input = ['a','a','a','b','b','b','b','c','c','c','a','a','c','d','d','d'];
Run Code Online (Sandbox Code Playgroud)
所以我的输出是只获得不同的值并进入一个新的向量.
var Output = SomeFunction(Input);
Run Code Online (Sandbox Code Playgroud)
这就是我要的:
Output = ['a','b','c','a','c','d'];
Run Code Online (Sandbox Code Playgroud)
Y尝试了这个,但不工作,以及:
function SomeFunction(input){
var out= [];
for (var i = 0; i < input.length - 1; i++) {
if(input[i] == input[i+1]){
out.push(input[i]);
}
}
return out;
}
Run Code Online (Sandbox Code Playgroud)
您可以使用 filter()
var input = ['a', 'a', 'a', 'b', 'b', 'b', 'b', 'c', 'c', 'c', 'a', 'a', 'c', 'd', 'd', 'd'];
input = input.filter(function(v, i, arr) {
return arr[i - 1] !== v;
//compare with the previous value
})
document.write(JSON.stringify(input));Run Code Online (Sandbox Code Playgroud)