I have a array of Object. There may be a case that one's type and session is completely equal to other object
[
{id:1, type:'a', section: [0,32]},
{id:2, type:'a', section: [0,32]},
{id:3, type:'b', section: [0,32]},
{id:4, type:'b', section: [35,45]},
{id:5, type:'c', section: [35,45]},
]
x.forEach(element => {
console.log(`type: ${element.type} and section: ${element.section} happened before`)
}
)
Whenever I find a unique object, I need to do some action.
The definition of unique object: Combination of type and session is never occurred
For example, in a loop of this array,
if I ecounter {id:1, type:'a', section: [0,32]} before, I would not do anything when coming across {id:2, type:'a', section: [0,32]}, coz type:'a', section: [0,32] was seen before.
However, I would do action in both cases {id:3, type:'b', section: [0,32]}, {id:4, type:'b', section: [35,45]}. Coz type:'b', section: [0,32]} is different than type:'b', section: [35,45]
Qesution: How could I achieve in one go without looping many times? like, one loop for extracting unique objects, another loop for action.
Edit
I come up with a solution so far, after seeing the advise from comment. Just see if there is better effective solution.
const x = [
{id:1, type:'a', section: [0,32]},
{id:2, type:'a', section: [0,32]},
{id:3, type:'b', section: [0,32]},
{id:4, type:'b', section: [35,45]},
{id:5, type:'c', section: [35,45]},
]
const map= new Map()
x.forEach(element => {
if (map.get(`${element.type}_${element.section}`)){
console.log(`type: ${element.type} and section: ${element.section} happened before`)
} else {
map.set(`${element.type}_${element.section}`, 1)
console.log(`type: ${element.type} and section: ${element.section}`)
}
})