Ben C
Ben C

Reputation: 351

Updating items in an array according to a specific sequence

I'm trying to update items in a dynamically-sized array according to the following sequence: 9th/10th, 19th/20th, 29th/30th, etc...

I've tried using modulo but I don't think that's exactly what I need.

Here's a simplified example of what I want to do

// my unchanged data
const before = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 11, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32]

// what I want
const after = [1, 2, 3, 4, 5, 6, 7, 8, '*', '*', 11, 12, 13, 14, 15, 16, 17, 18, '*', '*', 11, 22, 23, 24, 25, 26, 27, 28, '*', '*', 31, 32]

// looping through the array and need to make changes to the 9th/10th item, repeating
const attempt = before.map((arr, i) => {
  if (i !== 0 && (i % 8 === 0 || i % 9 === 0)) { // issue is here
    return '*'
  }
  return arr
})

console.log(attempt)

I should've paid more attention in school. Thanks for any help!

Upvotes: 1

Views: 90

Answers (1)

olgunyldz
olgunyldz

Reputation: 564

// my unchanged data
const before = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 11, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32]

// what I want
const after = [1, 2, 3, 4, 5, 6, 7, 8, '*', '*', 11, 12, 13, 14, 15, 16, 17, 18, '*', '*', 11, 22, 23, 24, 25, 26, 27, 28, '*', '*', 31, 32]

// looping through the array and need to apply special formatting to the 9th/10th item, repeating
const attempt = before.map((arr, i) => {
  if (arr !== 0 && (arr % 10 === 8 || arr % 10 === 9)) { // issue is here
    return '*'
  }
  return arr
})

console.log(attempt)

Upvotes: 3

Related Questions