Remove duplicates form an array
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);
Personally I don't see why everyone is getting all fancy with ES 6. If it were my code I'd prefer to support as many browsers as possible.
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"}
];
// Create array of unique names
var a = (function(a){
for (var i = array.length; i--;)
if (a.indexOf(array[i].name) < 0) a.push(array[i].name);
return a;
})([]);
console.log(a);
You could also simply combine map
with filter
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"}
];
var unique = array
.map( item => item.name )
.filter( ( item, idx, arr ) => arr.indexOf( item ) == idx )
console.log(unique)
If you are looking for a JavaScript solution that is not ES 6 (no Set) you can use the Array's reduce
method:
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"}
];
var names = array.reduce(function (a, b) {
if (a.indexOf(b.name) == -1) {
a.push(b.name)
}
return a;
}, []);
console.log(names);