使用纯Java脚本或打字稿删除数组中的重复项 [英] Remove Duplicate In Array Using Pure Javascript Or Typescript

查看:80
本文介绍了使用纯Java脚本或打字稿删除数组中的重复项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我似乎只找到使用其他JS库从数组中删除重复项的方法,但是由于我正在研究Angular项目,因此我希望使用纯JS或打字稿来实现.

I seem to only find ways to remove duplicates from an array using other JS libraries but I'm looking to do it in pure JS or typescript since I'm working on an Angular project.

我的问题是我可能会得到一个具有重复条目的数组,例如:

My problem is that I may get an array that has duplicate entries, such as this one:

data [0: {Id: 1, Definition: "House"},
      1: {Id: 1, Definition: "House"}]

我想过滤掉它,让我只得到

And I want to filter it out so that I only get

data [0: {Id: 1, Definition: "House"}]

我已经尝试过使用此方法,但仍然会得到重复的条目

I've tried it using this method but I still get duplicate entries

let uniqueArray = data.filter(function(item, pos) {
    return data.indexOf(item) == pos;
})

推荐答案

您可以通过这种方式实现所需的目标:

You can achieve what you want in this way:

您可以使用有些"

data = [{Id: 1, Definition: "House"}, {Id: 1, Definition: "House"}]

const finalOut = []
data.forEach((value) => {
    if (!finalOut.some(x=> (x.Id === value.Id || x.Definition === value.Definition))) 
   {
        finalOut.push(value)
    }
})

您也可以通过'实现此目标以干净优雅的方式减少':

You can also achieve this by 'reduce' in clean and elegant way:

const finalOut2 = data.reduce((acc, cur) => acc.some(x=> (x.Id === cur.Id || x.Definition === cur.Definition)) ? acc : acc.concat(cur), [])

如@Ezequiel所建议,在forEachreduce内使用some,使时间复杂度为n平方的 .对于较小的数据集,使用reducesome是一种不错的方法.但是,如果要处理非常长的数组,则必须避免 n平方时间复杂度的顺序.这是一种使用

As suggested by @Ezequiel using some inside forEach or reduce making the time complexity of order of n square. For smaller sets of data using reduce and some is an elegant approach. But if you are dealing with arrays of very large length, you must avoid order of n square time complexity Here is one such approach with filter:

//Here storing every value of data is inside lookupObj after filtering it. 
//And checking if value is filtered based on if key of the value inside lookupObj

const lookupObj = {} 
const finalOut3 = data.filter(
    x => {
        const is_unique = !(lookupObj[`Id_${x.Id}`] || lookupObj[`Id_${x.Definition}`])
        lookupObj[`Id_${x.Id}`] = true
        lookupObj[`Id_${x.Definition}`] = true
        return is_unique
    }
)

这篇关于使用纯Java脚本或打字稿删除数组中的重复项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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