Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
422 views
in Technique[技术] by (71.8m points)

javascript - How to remove repeated entries from an array while preserving non-consecutive duplicates?

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:

  • 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 like arr.slice(0, 3) and newB will be arr.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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Using array.filter() you can check if each element is the same as the one before it.

Something like this:

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...