Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

javascript - Remove duplicates form an array

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"];

I'm trying to do this with map:

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

But the problem is that this returns:

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

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.

Question&Answers:os

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

1 Answer

0 votes
by (71.8m points)

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);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...