我迄今所做的:提取数组排序列表的独特元素
var input = [1, 1, 3, 3, 3, 5, 5, 5, 9, 9, 9, 9];
var output = [];
/*input.forEach(function(element){ // works as intended, but I know we can do better :)
if(output.indexOf(element) == -1)
output.push(element);
});*/
output.push(input[0]); // first element is always unique!
for(var i=1; i<input.length; i++){ // check rest of the elements
if(input[i] != output[i-1])
output.push(input[i]);
}
console.log(output);
正如你可能已经注意到,我的逻辑是检查的input
的i+1th
元素等于output
的ith
元素,如果没有,将它添加到output
但是,此代码不起作用。它输出:[1, 3, 3, 3, 5, 5, 5, 9, 9, 9, 9]
。
我错过了什么?
哦JavaScript中,在所有其他语言,你很可能已经得到了当试图访问未写入还没有一个动态数组中的条目.. – amit