I am new to javascript and I tried like using distinct but its not what im looking for
example array:
let arr = [ {key:\"1\",value:\"dog\"},
You can map your objects to stringified versions of your objects so you can then use .indexOf
and .lastIndexOf()
to compare if the object found appears in different locations in your array, if the last and first index appear in the same location then it can be said that they're the same object (ie: a duplicate doesn't exist) and can be kept in your resulting array like so:
const arr = [{key:"1",value:"dog"},{key:"1",value:"dog"},{key:"2",value:"cat"},{key:"3",value:"bird"},{key:"3",value:"bird"}];
const searchable = arr.map(JSON.stringify);
const res = arr.filter((obj, i) => {
const str = JSON.stringify(obj);
return searchable.indexOf(str) === searchable.lastIndexOf(str);
});
console.log(res);
If you don't mind using a library, I strongly suggest using the "ramda" library.
const arr = [ {key:"1",value:"dog"}
, {key:"1",value:"dog"}
, {key:"2",value:"cat"}
, {key:"3",value:"bird"}
, {key:"3",value:"bird"}
];
const result = R.uniq(arr);
result will be:
[{"key": "1", "value": "dog"}, {"key": "2", "value": "cat"}, {"key": "3", "value": "bird"}]
you can use "lodash" or other similar libraries too.
You can use reduce
and Map
let arr = [{key:"1",value:"dog"},{key:"1",value:"dog"},{key:"2",value:"cat"},{key:"3",value:"bird"},{key:"3",value:"bird"}]
let mapper = arr.reduce( (op,inp) => {
let {key} = inp
op.set(key, op.get(key) || {value: inp, count:0})
op.get(key).count++
return op
},new Map())
let final = [...mapper.values()].reduce((op,{value,count}) => {
if(count === 1){
op.push(value)
}
return op
},[])
console.log(final)
Using the "find" method, you will get exactly what you are looking for "{key:"2",value:"cat"}".
arr.find((item, index) => {
const foundDup = arr.find((s, sIndex) => sIndex !== index && s.key === item.key);
return !foundDup;
});
If you can use Javascript libraries such as underscore or lodash, I recommend having a look at _.xorBy function in their libraries. From lodash:
_.xorBy([arrays], [iteratee=_.identity])
Basically, you pass in the array that in here is an object literal and you pass in the attribute that you want to all occurrences of remove duplicates with in the original data array, like this:
var data = [ {key:"1",value:"dog"}
, {key:"1",value:"dog"}
, {key:"2",value:"cat"}
, {key:"3",value:"bird"}
, {key:"3",value:"bird"}
];
var non_duplidated_data = _.xorBy(data, 'key');
Source - https://lodash.com/docs/4.17.14#xorBy