如何在保留非连续重复项的同时从数组中删除重复项? [英] How to remove repeated entries from an array while preserving non-consecutive duplicates?

查看:33
本文介绍了如何在保留非连续重复项的同时从数组中删除重复项?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个像 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:

  • 一一检查所有元素.
  • 如果元素与上一个元素相同,则对元素进行计数并执行类似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 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.

推荐答案

使用 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆