从数组中删除重复项 [英] Remove duplicates form an array

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

问题描述

我有一个看起来像这样的对象数组:

I have an array of objects that looks like this:

var array = [
    {id:123, value:"value1", name:"Name1"},
    {id:124, value:"value2", name:"Name1"},
    {id:125, value:"value3", name:"Name2"},
    {id:126, value:"value4", name:"Name2"}
    ...
];

如您所见,有些名称是重复的.我只想获得一个仅包含名称的新数组,但是如果某些名称重复,我不想再次添加它.我想要这个数组:

As you can see, some names are repeated. I want to get a new array with names only, but if some name repeats I don't want to add it again. I want this array:

var newArray = ["Name1", "Name2"];

我正在尝试使用map做到这一点:

I'm trying to do this with map:

var newArray = array.map((a) => {
    return a.name;
});

但是问题在于它返回:

newArray = ["Name1", "Name1", "Name2", "Name2"];

如何在map内设置一些条件,这样它不会返回已经存在的元素?我想使用map或其他一些ECMAScript  5或ECMAScript  6功能来做到这一点.

How can I set some condition inside map, so it won't return an element that already exists? I want to do this with map or some other ECMAScript 5 or ECMAScript 6 feature.

推荐答案

在ES6中,您可以使用

With ES6, you could use Set for unique values, after mapping only the names of the objects.

该提案使用传播语法... 用于将项目收集到新数组中.

This proposal uses a spread syntax ... for collecting the items in a new array.

const array = [{ id: 123, value: "value1", name:"Name1" }, { id: 124, value: "value2", name: "Name1" }, { id: 125, value: "value3", name: "Name2" }, { id: 126, value: "value4", name: "Name2" }],
      names = [...new Set(array.map(a => a.name))];

console.log(names);

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

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