Skip to content

Instantly share code, notes, and snippets.

@daltonmenezes
Last active April 5, 2020 23:00
Show Gist options
  • Save daltonmenezes/418a18185479611121e0bff0c8b8a917 to your computer and use it in GitHub Desktop.
Save daltonmenezes/418a18185479611121e0bff0c8b8a917 to your computer and use it in GitHub Desktop.
Filter an array of shallow objects by repeating and non-repeating objects in javascript
const objectList = [
{ id: 1, console: 'playstation 4' },
{ id: 2, console: 'xbox one s' },
{ id: 2, console: 'xbox one s' },
{ id: 1, console: 'playstation 4' },
{ id: 1, console: 'playstation 4' },
{ id: 1, console: 'playstation 2' },
{ id: 3, console: 'playstation 1' }
]
let filteredByRepetition = []
const filteredByNoRepetition =
objectList.reduce((acc, current) => {
const isAlreadyIn = acc.find(
obj => JSON.stringify(obj) === JSON.stringify(current)
)
if (isAlreadyIn) {
filteredByRepetition.push(isAlreadyIn)
return acc
}
return [...acc, current]
}, [])
console.log({
filteredByRepetition,
filteredByNoRepetition
})
/*
filteredByRepetition: Array[3]
0: Object
id: 2
console: "xbox one s"
1: Object
id: 1
console: "playstation 4"
2: Object
id: 1
console: "playstation 4"
filteredByNoRepetition: Array[4]
0: Object
id: 1
console: "playstation 4"
1: Object
id: 2
console: "xbox one s"
2: Object
id: 1
console: "playstation 2"
3: Object
id: 3
console: "playstation 1"
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment