Created
October 6, 2017 17:25
-
-
Save Woodsphreaker/92d26760c40f278bad0cb436e3a7bff5 to your computer and use it in GitHub Desktop.
filter duplicate objects
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const data = [ | |
{ name: "user1" , age: "20"}, | |
{ name: "user2" , age: "20"}, | |
{ name: "user1" , age: "20"}, | |
{ name: "user2" , age: "10"} | |
] | |
const filter = (data, type, field = "name") => { | |
const type1 = () => data.filter( ( el, i, arr ) => arr.findIndex( find => find[field] === el[field] ) === i ) | |
const type2 = () => Array.from( new Set( data.map( JSON.stringify ) ) ).map( JSON.parse ) | |
const type3 = () => data.filter( ( el, i, arr ) => arr.map( obj => obj[field] ).indexOf( el[field] ) === i ) | |
const types = { | |
type1, | |
type2, | |
type3 | |
} | |
return (types[type])() | |
} | |
console.log() | |
console.log(filter(data, "type1", "age")) | |
console.log() | |
console.log(filter(data, "type2")) | |
console.log() | |
console.log(filter(data, "type3")) | |
console.log() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment