Assuming I have the following:
var array =
[
{\"name\":\"Joe\", \"age\":17},
{\"name\":\"Bob\", \"age\":17},
{\"name\":\"Carl\
I know my code is little length and little time complexity but it's understandable so I tried this way.
I'm trying to develop prototype based function here and code also change.
Here,Distinct is my own prototype function.
<script>
var array = [{
"name": "Joe",
"age": 17
},
{
"name": "Bob",
"age": 17
},
{
"name": "Carl",
"age": 35
}
]
Array.prototype.Distinct = () => {
var output = [];
for (let i = 0; i < array.length; i++) {
let flag = true;
for (let j = 0; j < output.length; j++) {
if (array[i].age == output[j]) {
flag = false;
break;
}
}
if (flag)
output.push(array[i].age);
}
return output;
}
//Distinct is my own function
console.log(array.Distinct());
</script>
const x = [
{"id":"93","name":"CVAM_NGP_KW"},
{"id":"94","name":"CVAM_NGP_PB"},
{"id":"93","name":"CVAM_NGP_KW"},
{"id":"94","name":"CVAM_NGP_PB"}
].reduce(
(accumulator, current) => accumulator.some(x => x.id === current.id)? accumulator: [...accumulator, current ], []
)
console.log(x)
/* output
[
{ id: '93', name: 'CVAM_NGP_KW' },
{ id: '94', name: 'CVAM_NGP_PB' }
]
*/
If you have Array.prototype.includes or are willing to polyfill it, this works:
var ages = []; array.forEach(function(x) { if (!ages.includes(x.age)) ages.push(x.age); });
using lodash
var array = [
{ "name": "Joe", "age": 17 },
{ "name": "Bob", "age": 17 },
{ "name": "Carl", "age": 35 }
];
_.chain(array).pluck('age').unique().value();
> [17, 35]
i think you are looking for groupBy function (using Lodash)
_personsList = [{"name":"Joe", "age":17},
{"name":"Bob", "age":17},
{"name":"Carl", "age": 35}];
_uniqAgeList = _.groupBy(_personsList,"age");
_uniqAges = Object.keys(_uniqAgeList);
produces result:
17,35
jsFiddle demo:http://jsfiddle.net/4J2SX/201/
This is how you would solve this using new Set via ES6 for Typescript as of August 25th, 2017
Array.from(new Set(yourArray.map((item: any) => item.id)))