xxxxxxxxxx
const array = [{id: 1, name: "hello"}, {id: 2, name: "hii"}, {id: 1, name: "hey"} ];
const cleanArray = array.reduce((unique, o) => {
if(!unique.some(obj => obj.id === o.id)) {
unique.push(o);
}
return unique;
},[]);
xxxxxxxxxx
const arr = [{id: 1, name: 'one'}, {id: 2, name: 'two'}, {id: 1, name: 'one'}]
const ids = arr.map(o => o.id)
const filtered = arr.filter(({id}, index) => !ids.includes(id, index + 1))
console.log(filtered)
xxxxxxxxxx
let arr = [{name: "john"}, {name: "jane"}, {name: "imelda"}, {name: "john"}];
const uniqueArray = arr.filter((v,i,a)=>a.findIndex(t=>(t.name===v.name))===i)
console.log(uniqueArray);
xxxxxxxxxx
const addresses = [ ]; // Some array I got from async call
const uniqueAddresses = Array.from(new Set(addresses.map(a => a.id)))
.map(id => {
return addresses.find(a => a.id === id)
})
xxxxxxxxxx
let person = [
{name: "john"},
{name: "jane"},
{name: "imelda"},
{name: "john"},
{name: "jane"}
];
const obj = [new Map(person.map(item => [JSON.stringify(item), item])).values()];
console.log(obj);
xxxxxxxxxx
let person = [
{name: "john"},
{name: "jane"},
{name: "imelda"},
{name: "john"},
{name: "jane"}
];
const data = Array.from(new Set(person.map(JSON.stringify))).map(JSON.parse);
console.log(data);
xxxxxxxxxx
// remove duplicates objects from an array of objects using javascript
let arr = [
{id: 1, name: 'Chetan'},
{id: 1, name: 'Chetan'},
{id: 2, name: 'Ujesh'},
{id: 2, name: 'Ujesh'},
];
let jsonArray = arr.map(JSON.stringify);
console.log(jsonArray);
/*
[
'{"id":1,"name":"Chetan"}',
'{"id":1,"name":"Chetan"}',
'{"id":2,"name":"Ujesh"}',
'{"id":2,"name":"Ujesh"}'
]
*/
let uniqueArray = [new Set(jsonArray)].map(JSON.parse);
console.log(uniqueArray);
/*
[ { id: 1, name: 'Chetan' }, { id: 2, name: 'Ujesh' } ]
*/
xxxxxxxxxx
const uniqify = (array, key) => array.reduce((prev, curr) => prev.find(a => a[key] === curr[key]) ? prev : prev.push(curr) && prev, []);
xxxxxxxxxx
let days = ["senin","senin","selasa","selasa","rabu","kamis", "rabu"];
let fullname = [{name: "john"}, {name: "jane"}, {name: "imelda"}, {name: "john"},{name: "jane"}];
// REMOVE DUPLICATE FOR ARRAY LITERAL
const arrOne = new Set(days);
console.log(arrOne);
const arrTwo = days.filter((item, index) => days.indexOf(item) == index);
console.log(arrTwo);
// REMOVE DUPLICATE FOR ARRAY OBJECT
const arrObjOne = [new Map(person.map(item => [JSON.stringify(item), item])).values()];
console.log(arrObjOne);
const arrObjTwo = Array.from(new Set(person.map(JSON.stringify))).map(JSON.parse);
console.log(arrObjTwo);
xxxxxxxxxx
const arr = [
{ id: 1, name: "test1" },
{ id: 2, name: "test2" },
{ id: 2, name: "test3" },
{ id: 3, name: "test4" },
{ id: 4, name: "test5" },
{ id: 5, name: "test6" },
{ id: 5, name: "test7" },
{ id: 6, name: "test8" }
];
const filteredArr = arr.reduce((acc, current) => {
const x = acc.find(item => item.id === current.id);
if (!x) {
return acc.concat([current]);
} else {
return acc;
}
}, []);