如何保持数组的重复 [英] How to keep Duplicates of an Array

查看:93
本文介绍了如何保持数组的重复的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Javascript中,我试图只在一个数组中保留Duplicates。

In Javascript, I'm trying to only keep Duplicates in an Array.

例如我的初始数组是

[1,1,2,3,3,3,3,4,5,5]

结果应为

[1,3,5]

我尝试过使用.indexOf()和$ .inArray(),但无法理解出。我知道如何删除重复项,但保留它们非常困难。

I've tried working with .indexOf() and $.inArray(), but can't figure it out. I know how to remove Duplicates, but to keep them is quite difficult.

推荐答案

您可以通过检查项目是否为第一个,如果最后一个索引不是实际索引。

You could filter by checking if the item is the first one and if the last index is not the actual index.

var array = [1, 1, 2, 3, 3, 3, 3, 4, 5, 5],
    result = array.filter((a, i, aa) => aa.indexOf(a) === i && aa.lastIndexOf(a) !== i);

console.log(result);

这篇关于如何保持数组的重复的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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