如何从数组中删除重复的条目,同时保留非连续的重复项? [英] How to remove repeated entries from an array while preserving non-consecutive duplicates?
问题描述
我有一个像 var arr = [5,5,5,2,2,2,2,2,9,4,5,5,5]的数组;
我真的希望输出为 [5,2,9,4,5]
。我的理由是:
I have an array like var arr = [5, 5, 5, 2, 2, 2, 2, 2, 9, 4, 5, 5, 5];
I really want the output to be [5,2,9,4,5]
. My logic for this was:
- 逐个浏览所有元素。
- 如果element与prev元素相同,计算元素并执行类似
newA = arr.slice(i,count)
- 新数组应该只填充相同的元素。
- 对于我的示例输入,前3个元素是相同的,所以
newA
将类似于arr.slice( 0,3)
和newB
将是arr.slice(3,5)
和等等。
- Go through all the element one by one.
- If the element is the same as the prev element, count the element and do something like
newA = arr.slice(i, count)
- New array should be filled with just identical elements.
- For my example input, the first 3 elements are identical so
newA
will be likearr.slice(0, 3)
andnewB
will bearr.slice(3,5)
and so on.
我试图把它变成以下代码:
I tried to turn this into the following code:
function identical(array){
var count = 0;
for(var i = 0; i < array.length -1; i++){
if(array[i] == array[i + 1]){
count++;
// temp = array.slice(i)
}else{
count == 0;
}
}
console.log(count);
}
identical(arr);
我在确定如何输出代表一组相同元素的元素时遇到问题数组。如果元素不相同,则应按照原始数组中的顺序输出。
I am having problems figuring out how to output an element that represents a group of element that are identical in an array. If the element isn't identical it should be outputted in the order that it is in in the original array.
推荐答案
使用< a href =https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/Filter> array.filter()
你可以检查每个元素是否与之前的元素相同。
Using array.filter()
you can check if each element is the same as the one before it.
这样的东西:
var a = [5, 5, 5, 2, 2, 2, 2, 2, 9, 4, 5, 5, 5];
var b = a.filter(function(item, pos, arr){
// Always keep the 0th element as there is nothing before it
// Then check if each element is different than the one before it
return pos === 0 || item !== arr[pos-1];
});
document.getElementById('result').innerHTML = b.join(', ');
<p id="result"></p>
这篇关于如何从数组中删除重复的条目,同时保留非连续的重复项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!