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

114
Views
creating closure to increment index

method to create closure. Let's say I have a method to apply different colors to the object. and while mapping the array I have a lot of objects, so their indexes (in map operator) could be uncountable. I have 3 colors and I want to attach a property BG(background color) to them. Like 1st element has 1-st color, 2-nd = 2nd,. third = third, fourth = 1-st color, fifth = 2nd color.

Let's say I have indexes in my method 0, 1, 2, 3, 4, 5 ...

public sendIndex() {
    const users = this.users.map((user, index) => {
            if (!user.property) {
                this.currentIndex = index; // ?
                return {
                    ...user,
                    bg: this.transformIndex(index),
                };
            }
        });
}

public transformIndex(i) {
// index should be 0,1,2,3,4 ..... endless
}

I need to transform my indexes to the method to return index 0, 1, 2, and start again from 0,1,2 with saving globally current index

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

need to create map with key - as last index, and value as next index

const users = [{id: 1},{id: 2},{id: 3},{id: 4},{id: 5},{id: 6},{id: 7},{id: 8},{id: 9},{id: 10}];

const mapIndex = {
    2:0,
    1:2,
    0:1
  };
  
function transform() {
  let last = undefined;
return users.map(el => {
    last = last === undefined ? 0 : mapIndex[last]
    el.bg = last;
    return el;
})
}
  
  console.log(transform())

CSS SOLUTION

div {height: 20px;margin: 5px;}
div:nth-child(3n+1) {background: blue;}
div:nth-child(3n+2) {background: red;}
div:nth-child(3n+3) {background: green;}
<div> 1 blue</div>
<div>2 red</div>
<div>3 green</div>
<div>4 blue</div>
<div> 5 red</div>
<div> 6 green</div>
<div> 7 blue</div>
<div> 8 red</div>
<div> 9 green</div>

about 4 years ago · Juan Pablo Isaza Report
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!