1const array =
2 [
3 { "name": "Joe", "age": 17 },
4 { "name": "Bob", "age": 17 },
5 { "name": "Carl", "age": 35 }
6 ]
7
8const key = 'age';
9
10const arrayUniqueByKey = [...new Map(array.map(item =>
11 [item[key], item])).values()];
12
13console.log(arrayUniqueByKey);
14
15 /*OUTPUT
16 [
17 { "name": "Bob", "age": 17 },
18 { "name": "Carl", "age": 35 }
19 ]
20 */
21
22 // Note: this will pick the last duplicated item in the list.
1const data = [
2 { group: 'A', name: 'SD' },
3 { group: 'B', name: 'FI' },
4 { group: 'A', name: 'MM' },
5 { group: 'B', name: 'CO'}
6];
7const unique = [...new Set(data.map(item => item.group))]; // [ 'A', 'B']
1//ES6
2let array = [
3 { "name": "Joe", "age": 17 },
4 { "name": "Bob", "age": 17 },
5 { "name": "Carl", "age": 35 }
6];
7array.map(item => item.age)
8 .filter((value, index, self) => self.indexOf(value) === index)
9
10> [17, 35]
1function toUniqueArray(a){
2 var newArr = [];
3 for (var i = 0; i < a.length; i++) {
4 if (newArr.indexOf(a[i]) === -1) {
5 newArr.push(a[i]);
6 }
7 }
8 return newArr;
9}
10var colors = ["red","red","green","green","green"];
11var colorsUnique=toUniqueArray(colors); // ["red","green"]
1function unique(array, propertyName) {
2 return array.filter((e, i) => array.findIndex(a => a[propertyName] === e[propertyName]) === i);
3}
4