Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

145
Views
How to make a loop that can prevent action, when it meets elements that saw before

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}`)
  }
})
about 4 years ago · Santiago Gelvez
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!