[英]extracting unique elements from sorted list of array
到目前为止,我所做的是:
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
的ith
i+1th
元素是否等于output
的ith
元素,如果不相等,请将其添加到output
但是此代码不起作用。 它输出: [1, 3, 3, 3, 5, 5, 5, 9, 9, 9, 9]
。
我想念什么?
输出大小并不总是增加...应该是...
if(input[i]!=output[output.length-1])
如果将input[i]
与input[i-1]
进行比较,这会容易得多,例如:
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] != input[i-1]) // NOTE: changed output to input
output.push(input[i]);
}
这通常是完成操作的方式,因为通常您无权访问输出(例如,将其传递给进行进一步处理,而不是存储在数组中)。
查看output
中的最后一项时,需要使用output
的长度:
if(input[i] != output[output.length-1])
您可以通过按indexOf值过滤各项来返回每个值的第一项-
这样做的优点是不需要对列表进行排序。
var input = [5,9,5,3,9,3,5,1,3,9,9,1];
var output =input.filter(function(itm,i, A){
return A.indexOf(itm)==i;
});
output.sort()
/* returned value: (Array)
1,3,5,9
*/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.